Detailed operation process of Java connecting to SQL Server database
1. Specify the JDK version and download the driver
1.1 JDK version view
win + r输入cmd,命令窗口输入java --version
1.2 SQL Server official website download driver
SQL Server driver download direct address
下载完成后解压到自己熟悉的目录,不出意外的话你会看到以下文件
1.3 Load driver class
package com.alon.sqlutils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBCTest {
public static void main(String[] args) {
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String dburl = "jdbc:sqlserver://localhost:1433;DatabaseName = student;
String userName = "sa";//填写自己的数据库名称
String userPwd = "root";//数据库对应密码
try {
Class.forName(driverName);
System.out.println("连接成功!!!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("驱动加载失败");
}
try {
Connection dbcon = DriverManager.getConnection(dburl,userName,userPwd);
System.out.println("数据库连接成功!");
} catch (SQLException e) {
e.printStackTrace();
System.out.println("连接失败");
}
}
}
1.4 eclipse import driver jar package
目录结构
- Right-click the current project file, select
build path
, and selectAdd External Archive...
- Click to enter the ``Add External Archive...
,然后就会出现下图,选择一个符合你
JDk版本的
jar` package
- After the addition is completed, a directory will be automatically generated under the project directory
Reference Libraries
, and there will also be ajar
driver file
2. Run the program
不出意外的意外的话,你会看到
别慌先来看看网上的办法,找了一下午结果还没解决
, (I didn’t say that others are bad here, but it is aimed at my problem, which can’t be solved)
2.1 Final ending plan
只需要在上述驱动类代码中改一改就完美解决
··
2.2 Read data data
读取数据库数据代码
package com.alon.sqlutils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ReadDatabase {
public static void main(String[] args) {
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
// 方案一
String dburl = "jdbc:sqlserver://localhost:1433;DatabaseName = SQL_Road;encrypt=false";
String userName = "sa";
String userPwd = "root";
try {
Class.forName(driverName);
System.out.println("连接成功!!!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("驱动加载失败");
}
try {
Connection dbcon = DriverManager.getConnection(dburl,userName,userPwd);
System.out.println("数据库连接成功!");
//创建SQl命令对象
Statement stmt = dbcon.createStatement();
ResultSet rs = stmt.executeQuery("select * from Customers");
//循环读出每一条数据
while(rs.next()) {
System.out.println(rs.getInt("客户ID")+"\t" +rs.getString("姓名")+"\t"+rs.getString("地址"));
}
//关闭对象连接
stmt.close();
//关闭数据库连接
dbcon.close();
} catch (SQLException e) {
e.printStackTrace();
System.out.println("连接失败");
}
}
}
数据库数据展示
控制台读取数据展示