Java(32)_ JDBC向數據庫中插入數據


 

package MYSQK;
import java.sql.*;

/**
 * PreparedStatement 對象可以對sql語句進行預編譯,預編譯的信息會存在存儲該對象中,當相同的sql語句再次執行時,程序
 *   會使用PrepareStatement對象中,而不需再次編譯去查詢數據庫,大大提高了數據的訪問效率
 */

public class Insert {
    public  static  void main(String[] args) throws SQLException{
        Connection conn=null;
        PreparedStatement pst =null;

        try {
            // 1 加載驅動類
            Class.forName("com.mysql.jdbc.Driver");
            // 2 通過DriverManager獲取connection對象
             String url="jdbc:mysql://192.168.64.128:3306/jdbc?" +
                      "user=root&password=815qza&useUnicode=true&characterEncoding=UTF8";
             conn = DriverManager.getConnection(url);
             if (!conn.isClosed()){
                 System.out.println("Succeeded connecting to the Database!");
             }else{
                 System.out.println("Sorry,failed  connecting to the Database");
             }
             // 3 獲取pre對象
              String sql = "INSERT  INTO  USERS(name,PASSWORD,email,birthday) VALUES (?,?,?,?)";
               pst = conn.prepareStatement(sql);
             //為sql參數賦值
               pst.setString(1,"bowen5");
               pst.setString(2,"815qza");
               pst.setString(3,"bowen815@126.com");
               pst.setString(4,"1990-11-01");
             //4  使用prepare對象執行sql語句
               int count = pst.executeUpdate();
               System.out.println("影響數據庫的條數為:"+count);
             //5 操作result結果集
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }finally {
            // 6 關閉連接
             pst.close();
             conn.close();
        }
    }
}

 

 


免責聲明!

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



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