JDBC连接SQL Server典型程序
1. 建立数据库
在SQL Server中新建一个数据库,命名为test。
在此数据库中新建表emp,表结构为:

表中的内容为:

2. Java程序
下面是一个最典型的JDBC程序,从数据库中查询出所有记录并显示出来。
//STEP 1. Import required packages
import java.sql.*;
public class JDBCDemo {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
static final String DB_URL = "jdbc:sqlserver://localhost:1433;" + "databaseName=test;";
static final String USERNAME = "sa";
static final String PASSWORD = "";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// STEP 2: Register JDBC driver
Class.forName(JDBC_DRIVER);
// STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
// STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "select * from emp";
ResultSet rs = stmt.executeQuery(sql);
// STEP 5: Extract data from result set
while (rs.next()) {
// Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String name = rs.getString("name");
// Display values
System.out.print("ID: " + id);
System.out.print(", Name: " + name);
System.out.println(", Age: " + age);
}
// STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// finally block used to close resources
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
}// nothing we can do
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
3. 执行结果

备注:
1. 需要从微软官方网站下载JDBC驱动,sqljdbc.jar适用于jdk6.0以前的版本,如果jdk是6.0版本,则必须使用sqljdbc4.jar。
2. 请确保SQL Server的TCP/IP服务启用,端口为1433。具体查看方法如下:
SQL Server Configuration Manager => SQL Server网络配置 => 机器协议 => TCP/IP(右键属性) => IP地址 => IPALL => TCP动态端口(删除)=> TCP端口(1433或指定其它端口)。