Java sql server數據庫連接成功
阿新 • • 發佈:2018-08-09
ack query 數據庫連接 sage 給定 執行 sele oid 查詢語句
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; 12ResultSet 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 執行給定的 SQL 37 * 語句,該語句返回單個 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數據庫連接成功