使用jdbc向資料庫中注入大量資料(以10W條資料批量插入為例)
阿新 • • 發佈:2018-12-06
例項:10w條資料的插入(批量插入)
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class HomeWork02 { //預處理--注入資料 public static void main(String[]args) throws Exception { //載入資料庫 Class.forName("com.mysql.jdbc.Driver"); //獲取連線物件 String url = "jdbc:mysql://localhost:3306/db1?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=UTF-8"; Connection conn = DriverManager.getConnection(url, "username", "password"); //連線操作資料庫 String sql = "insert into homework VALUES (?,?,?) "; PreparedStatement pst = conn.prepareStatement(sql); for (int i = 1; i <= 100000 ; i++) { pst.setObject(1,i); pst.setObject(2,i+"號"); pst.setObject(3,i*10+"¥"); pst.addBatch(); } //操作完成,提交 pst.executeBatch(); //釋放資源 pst.close(); conn.close(); } }