標籤:串連失敗 對象 imp exce tac sql java res man
1 import java.sql.Connection; 2 import java.sql.SQLException; 3 import java.sql.Statement; 4 import java.sql.DriverManager; 5 import java.sql.ResultSet; 6 7 8 public class JavaE2 { 9 public static void main(String[] args) {10 Connection conn;11 Statement stmt;12 ResultSet rs;13 String url = "jdbc:sqlserver://localhost:1433;DatabaseName=test;";14 String sql = "select * from student";15 16 17 try {18 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 19 20 } catch (Exception ex) {21 System.out.println("資料庫載入失敗");22 }23 24 25 try {26 // 串連資料庫27 conn = DriverManager.getConnection(url, "sa", "sa");28 // 建立Statement對象29 stmt = conn.createStatement();30 /**31 * Statement createStatement() 建立一個 Statement 對象來將 SQL 陳述式發送到資料庫。32 */33 // 執行資料庫查詢語句34 rs = stmt.executeQuery(sql);35 /**36 * ResultSet executeQuery(String sql) throws SQLException 執行給定的 SQL37 * 語句,該語句返回單個 ResultSet 對象38 */39 while (rs.next()) {40 int id = rs.getInt("SID");41 String name = rs.getString("SNAME");42 int age = rs.getInt("SSEX");43 System.out.println("Sno:" + id + "\tSame:" + name + "\tSage:" + age);44 }45 if (rs != null) {46 rs.close();47 rs = null;48 }49 if (stmt != null) {50 stmt.close();51 stmt = null;52 }53 if (conn != null) {54 conn.close();55 conn = null;56 }57 } catch (SQLException e) {58 e.printStackTrace();59 System.out.println("資料庫連接失敗");60 }61 }62 }
Java sql server資料庫連接成功