Java

Java,第1张

Java 0.应用场景/报错场景:

用Windows身份验证连接查询数据库

Java eclipse → SQL Server 2016

0.0 如果没有下载sqljdbc,则先下载噢!

链接如下(Microsoft官网滴!):Download Microsoft SQL Server JDBC 驱动程序 6.0 from Official Microsoft Download Centerhttps://www.microsoft.com/zh-cn/download//confirm/iation.aspx?id=11774

 一般选第三个下载噢:

1.问题:

2.原因:

没有为集成身份验证配置驱动程序

3.解决:

找到下载的sqljdbc压缩包:

注意:x64表示64位,x86表示32位,根据自己电脑实际情况选择(我的电脑是Win10---64位)——如果电脑是64位 *** 作系统则复制auth下的x64文件夹的文件,如果电脑是32位 *** 作系统则复制auth下的x86文件夹的文件

注意:绝对路径是"C:WindowsSystem32sqljdbc_auth.dll"

 4.解决啦:

 5.附上完整代码供借鉴参考:

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中建立数据库建表录数据的代码:

CREATE DATAbase LibraryDB 
ON PRIMARY (
	NAME = 'LibraryDB',
	FILENAME = 'F:SQL ServerMSSQL13.MSSQLSERVERMSSQLDATALibraryDB.mdf',
	SIZE = 5MB,
	FILEGROWTH = 1MB,
	MAXSIZE = UNLIMITED
)
LOG ON	(
	NAME = 'LibraryDB_log',
	FILENAME = 'F:SQL ServerMSSQL13.MSSQLSERVERMSSQLDATALibraryDB_log.lof',
	SIZE = 3MB,
	FILEGROWTH = 1MB,
	MAXSIZE = 100MB
);


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));


INSERT INTO Student(Sno,Sname) VALUES ('000001','张三'),('000002','李四'),('000003','王五'),('000004','钱六');
INSERT INTO Student(Sno,Sname) VALUES ('000005','小明'),('000006','小红'),('000007','小刚'),('000008','小蓝');
SELECT * FROM Student;

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5697476.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存