sql server 2005 jdbc 连接

时间:2021-05-02 10:05:45

 

1.加载sql servser 2005 驱动(sqljdbc.jar),把驱动注册到driverManager

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

2.获得连接

conn = DriverManager.getConnection(url, user, password);

url="jdbc:sqlserver://localhost:1433; DatabaseName=数据库名称"

3.用预处理对象处理已经写好的sql

4.用预处理对象向sql传递参数(可选)

5.执行sql(查询用executeQuery();添加,删除,更新用executeUpdate())

Connection conn = null;
String url = "jdbc:sqlserver://localhost:1433; DatabaseName=test";
String user = "sa";
String password = "";
String sql = "select * from users ";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(url, user, password);
PreparedStatement pstm = conn.prepareStatement(sql);
ResultSet rs = pstm.executeQuery();
while(rs.next()){
System.out.println(rs.getString("account"));
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

 

若果sql servser 才安装好,运行时会报错,com.microsoft.sqlserver.jdbc.SQLServerException: 到主机 的 TCP/IP 连接失败。

解决办法:在所有程序中找到sql servser 2005 -配置工具-sql servser configuration manager-网络配置-MSSQLSERVER的协议-TCP/IP-右击设置为启用-重启服务,就解决了