驱动

在连接MS SQL 数据库上面,我们需要先下载所需的驱动包,驱动jar的可以在官网进行下载。 官网:https://docs.microsoft.com/en-us/sql/connect/jdbc/microsoft-jdbc-driver-for-sql-server

如果是使用Maven项目,这时我们需要添加相关的依赖配置:

1
2
3
4
5
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4.0</version>
</dependency>

连接

下面来展示使用Java 对MS SQL 数据库进行连接。
MSSQLJDBCUtil.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.devnp.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class MSSQLJDBCUtil {

private static String DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";

private static String URL = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=mloes-dev"; //连接URL
private static String USER_NAME = "sa"; // 数据库用户名
private static String PASSWORD = "!qaz2wsx"; // 数据库密码

public static void main(String[] args) {
// TODO Auto-generated method stub
Connection connection = getConnection() ;

if(connection == null)
System.out.println("Get MSSQL JDBC Connection Failed.");
else
System.out.println("Get MSSQL JDBC Connection Succeess.");
}

public static Connection getConnection() {

Connection connection = null;
try {
Class.forName(DRIVER);

connection = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}

public static void connectionClose(Connection connection) {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

}