java批量写入数据库

使用java.sql.DriverManager;进行数据批量写入
首先下载mysql-connect连接驱动包,https://dev.mysql.com/downloads/connector/j/5.1.html
将驱动包mysql-connector-j-8.2.0.jar放入项目lib下并右键选择add as library。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;


public class BatchSQLExample {

    public static void main(ArrayList<HashMap> args) {
        try {
            Connection Database_Connection = null;
            //mysql驱动
            String driver = "com.mysql.cj.jdbc.Driver";
            //测试驱动连接
            try{
                Class.forName(driver);
            }
            catch (ClassNotFoundException e){
                e.printStackTrace();
            }
            String url = "jdbc:mysql://localhost:3306/sakila?useOldAliasMetadataBehavior%3Dtrue%26serverTimezone%3DGMT%2B8%26useUnicode%3Dtrue%26characterEncoding%3DUTF-8%26useSSL%3Dfalse%26nullCatalogMeansCurrent%3Dtrue";
            String user = "root";
            String password = "123456";

            Database_Connection = DriverManager.getConnection(url, user, password);

            String sql = "INSERT INTO user (id, username) VALUES (?, ?)";
            PreparedStatement preparedStatement = Database_Connection.prepareStatement(sql);

            for (int i = 0; i < args.size(); i++) {
                System.out.println(i);
                HashMap tempmap1 = new HashMap();
                tempmap1 = args.get(i);
                preparedStatement.setInt(1, (int) tempmap1.get("id"));
                preparedStatement.setString(2, (String) tempmap1.get("username"));
                preparedStatement.addBatch();
            }
            int[] result = preparedStatement.executeBatch();

            System.out.println("Rows affected: " + result.length);

            preparedStatement.close();
            Database_Connection.close();

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

调用批量写入函数

BatchSQLExample batchsql = new BatchSQLExample();
ArrayList<HashMap> paramList = new ArrayList<>();
HashMap tempmap = new HashMap<>();
tempmap.put("id",1);
tempmap.put("username","hw");
paramList.add(tempmap);
tempmap = new HashMap<>();
tempmap.put("id",2);
tempmap.put("username","qyq");
paramList.add(tempmap);
System.out.println(paramList);
batchsql.main(paramList);
posted @ 2024-08-17 16:14  hanwang~  阅读(26)  评论(0编辑  收藏  举报