【JDBC】Extra02 SqlServer-JDBC
官网驱动获取地址:
https://www.microsoft.com/zh-cn/download/details.aspx
Maven仓库获取:
https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc
巨硬官网的太慢了我都还没下到,换成用中央仓库的了
POM坐标:
奇怪的是还区分了一些JRE版本,为了不出BUG我就对应的选了JRE8版本的
<!-- https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc --> <dependency> <groupId>com.microsoft.sqlserver</groupId> <artifactId>mssql-jdbc</artifactId> <version>8.4.1.jre8</version> </dependency>
链接测试类:
import org.junit.Test; import java.sql.Connection; import java.sql.DriverManager; /** * @author Administrator * @file IntelliJ IDEA SqlServer-JDBC * @create 2020 09 27 20:00 */ public class SqlServerJdbcTest { @Test public void connectionTest() throws Exception { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); final String URL = "jdbc:sqlserver://localhost:1433;DatabaseName=Test"; final String USERNAME = "sa"; final String PASSWORD = "123456"; Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); System.out.println(connection); connection.close(); } }
默认使用的用户名称是sa,没反应过来。。。
打印的链接对象:
ConnectionID:1 ClientConnectionId: f6e4ce24-c5db-4bcf-849b-bd6bc359013e Process finished with exit code 0
连接参数解耦剥离,老手艺了
sqlserver-jdbc.properties配置文件信息:
sqlServer.jdbc.driverClassName = com.microsoft.sqlserver.jdbc.SQLServerDriver sqlServer.jdbc.connectUrl = jdbc:sqlserver://localhost:1433;DatabaseName=Test sqlServer.jdbc.username = sa sqlServer.jdbc.password = 123456
连接工具类:
package cn.zeal4j.util; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; /** * @author Administrator * @file IntelliJ IDEA SqlServer-JDBC * @create 2020 09 27 20:13 */ public class SqlServerUtil { private SqlServerUtil() {} private static String connectUrl; private static String username; private static String password; static { try { InputStream resourceAsStream = SqlServerUtil.class.getClassLoader().getResourceAsStream("sqlserver-jdbc.properties"); Properties properties = new Properties(); properties.load(resourceAsStream); Class.forName(properties.getProperty("sqlServer.jdbc.driverClassName")); connectUrl = properties.getProperty("sqlServer.jdbc.connectUrl"); username = properties.getProperty("sqlServer.jdbc.username"); password = properties.getProperty("sqlServer.jdbc.password"); } catch (Exception exception) { exception.printStackTrace(); } } public static Connection getConnection() { try { return DriverManager.getConnection(connectUrl, username, password); } catch (SQLException throwables) { throwables.printStackTrace(); } return null; } }
封装之后的测试单元:
@Test public void connectionTest2() throws Exception { Connection connection = SqlServerUtil.getConnection(); System.out.println(connection); connection.close(); }