java连接sqlserver2008

时间:2021-06-05 08:59:50

java连接sqlserver2008时应有sqljdbc4.jar驱动包。连接的示例代码如下:

import java.sql.*;

public class ConnectSQL {

	public static void main(String[] args) {

		try{
String driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";
Class.forName(driver); //加载驱动
String url="jdbc:sqlserver://localhost:1433;"+
"DatabaseName=UserInfo";
Connection conn=DriverManager.getConnection(url,"sa","123");//建立连接
Statement stmt=conn.createStatement();//创建状态
String sql="select * from userInfo";
ResultSet rs=stmt.executeQuery(sql);//执行查询
while(rs.next()){
System.out.println(rs.getInt(1)+","+rs.getString(2)+","+
rs.getString(3)+","+rs.getInt(4)+","+rs.getInt(5));
}
rs.close();
stmt.close();
conn.close();//善后
}
catch(Exception e){
e.printStackTrace();
} }