java對sql server的增刪改查


 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         //成功-返回false
41         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         //成功-返回false
53         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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM