import java.sql.*;
public class DataBase {
public static void main(String[] args){
Connection ct=null;
Statement sm=null;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
ct=DriverManager.getConnection("jdbc:odbc:sql server","sa","rengui987426.");
sm=ct.createStatement();
ResultSet rs=sm.executeQuery("select * from bumen");
while(rs.next()){
int ners=rs.getInt(1);
String ner=rs.getString(2);
String didian=rs.getString(3);
System.out.println(ners+" "+ner+" "+didian);
}
}catch(Exception e){
System.out.println("錯誤");
}finally{
try{
if(ct!=null){
ct.close();
}
if(sm!=null){
sm.close();
}
}catch(Exception e){}
}
}
}
連接sql server時運行catch語句,運行結果為:錯誤
看看我的代碼哪兒出問題了?
public static void main(String[] args) {
// TODO 自動生成的方法存根
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String dbURL = "jdbc:sqlserver://localhost:1433;DatabaseName=test";
String userName = "sa";
String userPwd = "dsghsdgh";
try{
Class.forName(driverName);
System.out.println("加載驅動成功!");
}catch(Exception e){
e.printStackTrace();
System.out.println("加載驅動失敗!");
}
try{
@SuppressWarnings("unused")
Connection dbConn = DriverManager.getConnection(dbURL,userName,userPwd);
System.out.println("連接數據庫成功!");
}catch(Exception e){
e.printStackTrace();
System.out.println("SQL Server連接失敗!");
}
}
先測試是否能夠加載驅動,測試是否能連接數據庫,再測試讀取數據,你的try不利於查看問題的所在