下载官方jdbc,解压后里面有例子。有jre7和jre8的driver的jar。
跑连接例子的时候报错
- com.microsoft.sqlserver.jdbc.SQLServerException: 通过端口 1433 连接到主机 localhost 的 TCP/IP 连接失败。错误:“connect timed out。请验证连接属性。确保 SQL Server 的实例正在主机上运行,且在此端口接受 TCP/IP 连接,还要确保防火墙没有阻止到此端口的 TCP 连接。”。
https://blog.youkuaiyun.com/niaonao/article/details/53897486 可以 - 警告: Failed to load the sqljdbc_auth.dll cause : no sqljdbc_auth in java.library.path
解决办法:将sqljdbc_auth.dll拷贝到C:\Windows\System32目录下即可解决
https://blog.youkuaiyun.com/tingzhiyi/article/details/52086662
//=====================================================================
//
// File: connectURL.java
// Summary: This Microsoft JDBC Driver for SQL Server sample application
// demonstrates how to connect to a SQL Server database by using
// a connection URL. It also demonstrates how to retrieve data
// from a SQL Server database by using an SQL statement.
//
//---------------------------------------------------------------------
//
// This file is part of the Microsoft JDBC Driver for SQL Server Code Samples.
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// This source code is intended only as a supplement to Microsoft
// Development Tools and/or on-line documentation. See these other
// materials for detailed information regarding Microsoft code samples.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
//=====================================================================
import java.sql.*;
public class connectURL {
public static void main(String[] args) {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
"databaseName=mytzzy;integratedSecurity=true;";
// 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 ejpt";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
// Iterate through the data in the result set and display it.
while (rs.next()) {
System.out.println(rs.getString(1) + " " + rs.getString(2));
}
}
// 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) {}
}
}
}