试了很多次了,还是不行
public class MySqlDemo {
public static void main(String[] args) {
//Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://localhost:1433;DatabaseName=db_mysise";
String user="root";
String password="12345";
Connection conn= null;
Statement stat=null;
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn=DriverManager.getConnection(url,user,password);
stat=conn.createStatement();
String sql="select * from student";
ResultSet rs=stat.executeQuery(sql);
System.out.println("学号\t\t"+"姓名\t"+"性别\t"+"年龄\t"+"专业\t\t\t"+"宿舍");
while(rs.next()){
String num=rs.getString("学号");
String name=rs.getString("姓名");
String sex=rs.getString("性别");
String age=rs.getString("年龄");
String major=rs.getString("专业");
String dorm=rs.getString("宿舍");
System.out.println(""+num+"\t"+name+"\t"+sex+"\t"+age+"\t"+major+"\t"+dorm);
}
rs.close();
stat.close();
conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
结果
com.microsoft.sqlserver.jdbc.SQLServerException: 到主机 的 TCP/IP 连接失败。 java.net.ConnectException: Connection refused: connect
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.loginWithoutFailover(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at com.sise.testdemo.MySqlDemo.main(MySqlDemo.java:32)