我使用 sqlite 来存储聊天历史记录我现在担心天气我的方法是线程安全的。
下面的方法是我用来将我的消息添加到数据库的方法。
我的方法是线程安全的吗?
public class dbHistory {
public synchronized void addMessage(String from, String agentName, String msg, String time, String channel) {
try {
String databaseFileLocation = "jdbc:sqlite:history_" + agentID + ".db";
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection(databaseFileLocation);
PreparedStatement prep = conn.prepareStatement("insert into history values (?, ?, ?, ?, ?);");
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Calendar cal = Calendar.getInstance();
prep.setString(1, channel);
prep.setString(2, from);
prep.setString(3, msg);
prep.setString(4, agentName);
prep.setString(5, dateFormat.format(cal.getTime()));
prep.addBatch();
conn.setAutoCommit(false);
prep.executeBatch();
conn.setAutoCommit(true);
conn.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
}