標籤:color 取數 ext rgs 取資料 更新 語句 載入 exce
1 package Database; 2 import java.sql.*; 3 public class DBUtil { 4 //這裡可以設定資料庫名稱 5 private final static String URL = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=mythree"; 6 private static final String USER="sa"; 7 private static final String PASSWORD="123"; 8 private static Connection conn=null; 9 //靜態代碼塊(將載入驅動、串連資料庫放入靜態塊中) 10 static{ 11 try { 12 13 //1.載入驅動程式14 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 15 //2.獲得資料庫的串連16 conn=(Connection)DriverManager.getConnection(URL,USER,PASSWORD); 17 } 18 catch (ClassNotFoundException e) {19 e.printStackTrace(); 20 } catch (SQLException e) {21 e.printStackTrace(); 22 }23 } 24 //對外提供一個方法來擷取資料庫連接25 public static Connection getConnection(){26 return conn; 27 }28 //查詢29 public void select(Statement stmt) throws SQLException {30 ResultSet rs = stmt.executeQuery("select * from 李運辰.選課"); 31 while(rs.next()){32 //如果對象中有資料,就會迴圈列印出來33 System.out.println("學號="+rs.getInt("學號")+"課程編號="+rs.getInt("課程編號")+"考試成績="+rs.getInt("考試成績"));34 35 //System.out.println(rs.getInt("教師編號")+","+rs.getString("姓名")+","+rs.getInt("專業")); 36 } 37 }38 //插入39 public void insert(Statement stmt) throws SQLException {40 //成功-返回false41 boolean execute = stmt.execute("insert into 李運辰.選課 values(1,2,100)");42 System.out.println(execute);43 }44 //更新45 public void update(Statement stmt) throws SQLException {46 //返回序號47 int executeUpdate = stmt.executeUpdate("update 李運辰.選課 set 考試成績=90 where 學號=1 "); 48 System.out.println(executeUpdate);49 }50 //刪除51 public void delete(Statement stmt) throws SQLException {52 //成功-返回false53 boolean execute = stmt.execute("delete from 李運辰.選課 where 學號=11 and 課程編號=2");54 System.out.println(execute);55 }56 //測試案例57 public static void main(String[] args) throws Exception{ 58 DBUtil d = new DBUtil();59 //3.通過資料庫的串連操作資料庫,實現增刪改查 60 Statement stmt = conn.createStatement(); 61 //ResultSet executeQuery(String sqlString):執行查詢資料庫的SQL語句 ,返回一個結果集(ResultSet)對象。62 //d.insert(stmt);63 //d.update(stmt);64 d.delete(stmt);65 d.select(stmt);66 67 } 68 69 70 }
java對sql server的增刪改查