java jdbc 連接數據庫是入門級的數據庫實驗,之所以在這裏把代碼貼出來 是爲了 方便以後閱讀。
package com;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DbStoreHelper {
private String insert_sql;
private String connectStr;
private String username;
private String password;
private Connection conn = null;
private PreparedStatement psts = null;
private static DbStoreHelper _instance = null;
private static int count = 0;
private static int tot = 0;
private static Object lock = new Object();
private final static int every_time = 20000;
public static DbStoreHelper get() {
if (_instance == null) {
return _instance = new DbStoreHelper();
}
return _instance;
}
private DbStoreHelper() {
}
public void addPacket(Persons item) throws SQLException {
synchronized (lock) {
if (count == 0) {
try {
init();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
count++;
psts.setString(1,item.id);
psts.setString(2,item.time);
psts.setString(3,item.name);
psts.setString(4,item.gender);
psts.setString(5,item.sign);
psts.setDouble(6,item.latitude);
psts.setDouble(7,item.longitude);
psts.setInt(8,item.dis);
psts.addBatch();
if (count == every_time) {
tot++;
System.out.println("commit : " + count * tot);
//long start = System.currentTimeMillis();
count = 0;
commit();
//long end = System.currentTimeMillis();
//System.out.println("cost time : " + (end - start) / (1000)
// + "s");
}
}
}
public void commit() throws SQLException {
psts.executeBatch(); //批量執行
conn.commit(); //批量提交
conn.close();
}
private void init() throws ClassNotFoundException, SQLException {
connectStr = "jdbc:mysql://localhost:3306/"+FinalUtil.database+"?useServerPrepStmts=false&rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf8mb4&charset=utf8mb4";
//指定編碼方式連接數據庫
insert_sql = "INSERT INTO "+FinalUtil.new_table_name+" VALUES (?,?,?,?,?,?,?,?)";
username = "root";//用戶名
password = "111111";//密碼
Class.forName("com.mysql.jdbc.Driver");//加載數據驅動
//初始化連接
conn = DriverManager.getConnection(connectStr, username, password);
conn.setAutoCommit(false); //設置手動提交
//獲取操作對象
psts = conn.prepareStatement(insert_sql);
}
}
select * from limit 20 offset 10
意思是 從 第10行開始,查找20行