多线程存数据mysql_java 多线程存储数据库
展開全部
以mysql為數(shù)據(jù)庫(kù)32313133353236313431303231363533e4b893e5b19e31333332616431寫的一個(gè)粗陋的demo,你參考一下,希望不會(huì)因?yàn)榇a過多被百度吞了——
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
allotThread();
}
/**
* 將100條數(shù)據(jù)分成10份并啟動(dòng)10個(gè)線程分別操作
*/
public static void allotThread() {
List datas = buildDatas();
for (int i=0; i<100; i+=10) {
List tenDatas = datas.subList(i, i + 10);
insertData(tenDatas);
}
}
/**
* 創(chuàng)建100條模擬數(shù)據(jù)
* @return
*/
public static List buildDatas() {
List datas = new ArrayList();
for (int i=0; i<100; i++) {
String[] data = {"id " + i, "name " + i};
datas.add(data);
}
return datas;
}
/**
* 啟動(dòng)線程進(jìn)行數(shù)據(jù)插入操作
* @param tenDatas
*/
public static void insertData(final List tenDatas) {
new Thread(new Runnable() {
public void run() {
String sql = "insert into testtable (id, name) values (?, ?)";
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
conn.setAutoCommit(false);
pstmt = getPstmt(conn, sql);
for (String[] data : tenDatas) {
pstmt.setString(1, data[0]);
pstmt.setString(2, data[1]);
pstmt.addBatch();
}
pstmt.executeBatch();
conn.commit();
conn.setAutoCommit(true);
} catch (SQLException e) {
e.printStackTrace();
rollback(conn);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
close(pstmt);
close(conn);
}
}
}).start();
}
public static Connection getConnection() throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
String dbUrl = "jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=UTF-8";
Connection conn = DriverManager.getConnection(dbUrl, "root", "tooeasy");
return conn;
}
public static PreparedStatement getPstmt(Connection conn, String sql) throws SQLException, ClassNotFoundException {
PreparedStatement pstmt = conn.prepareStatement(sql);
return pstmt;
}
public static void rollback(Connection conn) {
try {
if (null != conn) {
conn.rollback();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(Connection conn) {
try {
if (null != conn) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(PreparedStatement pstmt) {
try {
if (null != pstmt) {
pstmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(ResultSet rs) {
try {
if (null != rs) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
總結(jié)
以上是生活随笔為你收集整理的多线程存数据mysql_java 多线程存储数据库的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: redis 主从模式_Redis主从模式
- 下一篇: python中函数的使用_python中