最近須要測試日誌查詢性能的,感受比較慢全部須要進行大數據量的數據進行測試,發現mysql的批量導入數據很強悍,導入10萬條數據,只要15596ms。java
其中須要注意的一下幾點:mysql
1.提交方式須要設置爲手動提交:sql
conn.setAutoCommit(false); // 設置手動提交 數據庫
2. 採用mysql的批量導入語句:app
pstmt.addBatch();性能
pstmt.executeBatch(); // 執行批量處理 測試
以後再提交: 大數據
conn.commit(); // 提交 ui
3.將mysql批量導入功能開啓:url
在mysql的jdbc.url地址中添加參數:
useServerPrepStmts=false&rewriteBatchedStatements=true&useSSL=false
結果展現:
代碼以下:
/**
* 查詢數據庫中配置的分館信息
*/
public static void insertTestData(){
long begint = System.currentTimeMillis();
System.out.println("========開始導入時間:"+begint+"=================");
PreparedStatement pstmt = null;
ResultSet rs = null;
Connection conn = null;
int count = 100000;
try {
String insertSql = "";
insertSql = "INSERT INTO user_access_log(uid,cn,appName,port,serverIP,userIP,createDate,operation,details,signature) VALUES (?,?,?,?,?,?,?,?,?,?)";
conn = getMysqlConnect("audit");
conn.setAutoCommit(false); // 設置手動提交
System.out.println("============insertSql:"+insertSql+"======================");
pstmt = conn.prepareStatement(insertSql,Statement.RETURN_GENERATED_KEYS);
for (int i = 0; i < count; i++) {
pstmt.setString(1, "test02");
pstmt.setString(2, "test02");
pstmt.setString(3, "sso");
pstmt.setInt(4, 80);
pstmt.setString(5, "127.0.0.1");
pstmt.setString(6, "172.16.208.99");
pstmt.setDate(7, new java.sql.Date(System.currentTimeMillis()));
pstmt.setInt(8, 0);
pstmt.setString(9, "test02正常登陸"+i);
pstmt.setString(10, null);
pstmt.addBatch();
if( i%1000 == 0 ){
pstmt.executeBatch(); // 執行批量處理
}
}
pstmt.executeBatch(); // 執行批量處理
conn.commit(); // 提交
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(pstmt != null){
pstmt = null;
}
if(rs != null){
rs = null;
}
if(conn != null){
conn = null;
}
}
long endt = System.currentTimeMillis();
System.out.println("========結束導入時間:"+endt+"=================");
System.out.println("========導入數據"+count+"條共耗時間:"+(endt-begint)+"ms=================");
}
/**
* 根據mysql配置文件獲取數據庫鏈接
*/
public static Connection getMysqlConnect(String dbname){ Connection con = null; String username = ""; String password = ""; String url = null; String address = ""; String port = ""; try { PropertyParser pParser = new PropertyParser(Const.ROOTPATH + "logconfig.properties"); url = pParser.getValue("db.url"); address = url.substring((url.indexOf("/") + 2), url .lastIndexOf(":")); port = url.substring((url.lastIndexOf(":") + 1), url .lastIndexOf("/")); username = pParser.getValue("db.user"); password = pParser.getValue("db.password"); Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://" + address + ":"+ port + "/"+dbname+"?useServerPrepStmts=false&rewriteBatchedStatements=true&useSSL=false&user="+username+"&password="+password+"&useUnicode=true&characterEncoding=UTF-8"); } catch (IOException e1) { e1.printStackTrace(); return null; } catch (ClassNotFoundException e2) { e2.printStackTrace(); return null; } catch (SQLException e3) { e3.printStackTrace(); return null; } return con; }