3.设置SQL SERVER 2005的参数。
(1)打开SQL Server Configuration Manager
(2)打开SQL Server 2005网络配置->MSSQLSERVER的协议->TCP/IP,双击进入,在IP地址一栏中,把相应的端口号改成1433,再重启服务(remember!)
4.程序连接测试代码:
public class Main {
private String url="jdbc:sqlserver://localhost:1433;databaseName=Test";
private String userName="sa";
private String password="abc";
private Connection con;
public Main(){
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con=DriverManager.getConnection(url,userName,password);
} catch (ClassNotFoundException ex) {
System.out.println("Error:Can't Load the SQL Server Driver");
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}catch(SQLException ex){
System.out.println("Error:Can't connect to Database!");
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) {
Main main=new Main();
String sql="select * from Student";
if(main.con==null)
return;
try{
Statement st=main.con.createStatement();
ResultSet rs=st.executeQuery(sql);
while(rs.next()){
System.out.println(rs.getString(1)+","+rs.getString(2)+","+rs.getString(3)+","+rs.getString(4));
}
}catch(SQLException e){
e.printStackTrace();
}
}
}