用Windows身份验证连接查询数据库
Java eclipse → SQL Server 2016
链接如下(Microsoft官网滴!):Download Microsoft SQL Server JDBC 驱动程序 6.0 from Official Microsoft Download Centerhttps://www.microsoft.com/zh-cn/download/confirmation.aspx?id=11774
一般选第三个下载噢:
没有为集成身份验证配置驱动程序
找到下载的sqljdbc压缩包:
注意:x64表示64位,x86表示32位,根据自己电脑实际情况选择(我的电脑是Win10---64位)——如果电脑是64位操作系统则复制auth下的x64文件夹的文件,如果电脑是32位操作系统则复制auth下的x86文件夹的文件
注意:绝对路径是"C:\Windows\System32\sqljdbc_auth.dll"
java(eclipse)中连接java和SQL server的代码:
package test_jdbc; import java.sql.*; public class Test_connectURL { public static void main(String[] args) { // Create a variable for the connection string. String connectionUrl = "jdbc:sqlserver://localhost:1433;DatabaseName=LibraryDB;integratedSecurity=true;"; //DatabaseName=自己的数据库名称;integratedSecurity=true表示使用Windows身份验证 // Declare the JDBC objects. Connection con = null; Statement stmt = null; ResultSet rs = null; try { // Establish the connection. Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); con = DriverManager.getConnection(connectionUrl); // Create and execute an SQL statement that returns some data. String SQL = "SELECT * FROM Student"; //写自己需要的查询语句噢 stmt = con.createStatement(); rs = stmt.executeQuery(SQL); System.out.println("学号\t姓名\t信用度"); //写自己需要的标题噢 // Iterate through the data in the result set and display it. while (rs.next()) { System.out.println(rs.getString("Sno") + "\t" + rs.getString("Sname") + "\t" + rs.getString("Credit")); //根据自己查询的内容结果写打印内容噢 } } // Handle any errors that may have occurred. catch (Exception e) { e.printStackTrace(); } finally { if (rs != null) try { rs.close(); } catch (Exception e) { } if (stmt != null) try { stmt.close(); } catch (Exception e) { } if (con != null) try { con.close(); } catch (Exception e) { } } } }
SQL server中建立数据库建表录数据的代码:
/* 创建数据库:注意修改两个FILENAME下的文件路径噢!根据自己的设置修改! */ CREATE DATABASE LibraryDB ON PRIMARY ( NAME = 'LibraryDB', FILENAME = 'F:\SQL Server\MSSQL13.MSSQLSERVER\MSSQL\DATA\LibraryDB.mdf', SIZE = 5MB, FILEGROWTH = 1MB, MAXSIZE = UNLIMITED ) LOG ON ( NAME = 'LibraryDB_log', FILENAME = 'F:\SQL Server\MSSQL13.MSSQLSERVER\MSSQL\DATA\LibraryDB_log.lof', SIZE = 3MB, FILEGROWTH = 1MB, MAXSIZE = 100MB ); /* 建表:Student,Book,Borrow,Renew,Back(这里只放Student表啦) */ USE LibraryDB; DROP TABLE IF EXISTS Student; CREATE TABLE Student( Sno char(6), Sname varchar(30) DEFAULT NULL, Password char(6) DEFAULT '111111', Credit int DEFAULT 100, PRIMARY KEY(Sno)); /* 录入初始数据:Student,Book,Borrow(这里只放Student表啦) */ INSERT INTO Student(Sno,Sname) VALUES ('000001','张三'),('000002','李四'),('000003','王五'),('000004','钱六'); INSERT INTO Student(Sno,Sname) VALUES ('000005','小明'),('000006','小红'),('000007','小刚'),('000008','小蓝'); SELECT * FROM Student;