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(); } } }