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();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章