jdbc批量添加數據

private static String url="jdbc:mysql://localhost:3306/test2?useUnocode=true&characterEncoding=utf-8";
    private static String username="root";
    private static String password="123456";
    public static void main(String[] args) throws Exception {
        //1 加載驅動
        Class.forName("com.mysql.jdbc.Driver");
        //2 獲取連接
        Connection con = DriverManager.getConnection(url,username,password);
        //3 執行sql
        String sql = "insert into student (sname,age) values('白1','18')";
        Statement sm = con.createStatement();
        sm.addBatch(sql);//添加第1條sql語句
        sql = "insert into student (sname,age) values('白2','28')";
        sm.addBatch(sql);//添加第2條sql語句
        //設置?的值.序號從1開始
        //4 執行sql,返回影響的行數
        int[] counts = sm.executeBatch();//只能執行增刪改.
        for(int count:counts){
            System.out.println("影響行數:"+count);
        }
        sm.close();
        con.close();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章