JDBC向數據庫中寫數據

 1 package MYSQK;
 2 import java.sql.*;
 3 
 4 /**
 5  * PreparedStatement 對象能夠對sql語句進行預編譯,預編譯的信息會存在存儲該對象中,當相同的sql語句再次執行時,程序
 6  *   會使用PrepareStatement對象中,而不需再次編譯去查詢數據庫,大大提升了數據的訪問效率
 7  */
 8 
 9 public class Insert {
10     public  static  void main(String[] args) throws SQLException{
11         Connection conn=null;
12         PreparedStatement pst =null;
13 
14         try {
15             // 1 加載驅動類
16             Class.forName("com.mysql.jdbc.Driver");
17             // 2 經過DriverManager獲取connection對象
18              String url="jdbc:mysql://192.168.64.128:3306/jdbc?" +
19                       "user=root&password=815qza&useUnicode=true&characterEncoding=UTF8";
20              conn = DriverManager.getConnection(url);
21              if (!conn.isClosed()){
22                  System.out.println("Succeeded connecting to the Database!");
23              }else{
24                  System.out.println("Sorry,failed  connecting to the Database");
25              }
26              // 3 獲取pre對象
27               String sql = "INSERT  INTO  USERS(name,PASSWORD,email,birthday) VALUES (?,?,?,?)";
28                pst = conn.prepareStatement(sql);
29              //爲sql參數賦值
30                pst.setString(1,"bowen5");
31                pst.setString(2,"815qza");
32                pst.setString(3,"bowen815@126.com");
33                pst.setString(4,"1990-11-01");
34              //4  使用prepare對象執行sql語句
35                int count = pst.executeUpdate();
36                System.out.println("影響數據庫的條數爲:"+count);
37              //5 操做result結果集
38         }catch (ClassNotFoundException e){
39             e.printStackTrace();
40         }finally {
41             // 6 關閉鏈接
42              pst.close();
43              conn.close();
44         }
45     }
46 }
相關文章
相關標籤/搜索