我在網路上搜尋了N天,幾乎沒有關於線程安全的解決辦法,同樣的問題Redis就很好解決,改了一個網上找來的工具類,請懂的大神幫我修改一下或者給點指導意見.我現在的想法就是加了synchronized關鍵字,但是總覺得還是有問題,非常感謝!
class MySQLUtil {
private static final String driver = "com.mysql.jdbc.Driver";
private static final String url = "jdbc:mysql://192.168.31.103:3306/";
private static final String character = "?useUnicode=true&characterEncoding=utf8";
private static final String ssl = "&useSSL=false";
private static final String user = "root";
private static final String password = "111111";
private static Connection connection = null;
private static Statement statement = null;
private static PreparedStatement ps = null;
private static ResultSet rs = null;
boolean TestConnection(String db) {
try {
Class.forName(driver);
Connection connection = DriverManager.getConnection(url + db + character + ssl, user, password);
if (!connection.isClosed()) {
CloseConnection();
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
synchronized private void ConnectToDB(String db) {
try {
Class.forName(driver);
Connection connection = DriverManager.getConnection(url + db + character + ssl, user, password);
if (!connection.isClosed()) {
statement = connection.createStatement();
}
} catch (Exception e) {
e.printStackTrace();
}
}
synchronized private void CloseConnection() {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
synchronized void ModifyData(String db, String data) {
ConnectToDB(db);
try {
statement.execute(data);
} catch (SQLException e) {
e.printStackTrace();
} finally {
CloseConnection();
}
}
synchronized List ReadData(String db, String data) {
List<String> list = new ArrayList<>();
int count;
ConnectToDB(db);
try {
rs = statement.executeQuery(data);
ResultSetMetaData rsmd;
rsmd = rs.getMetaData();
count = rsmd.getColumnCount();
while (rs.next()) {
for (int i = 1; i <= count; i++) {
String label = rsmd.getColumnLabel(i);
list.add(label);
String value = rs.getString(i);
list.add(value);
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
CloseConnection();
}
return list;
}
}
為了確保連接間資料獨立(非共享),我猜你想實現連接池:
稍微修改了下,可能會好一些,建議還是聽上面那哥們的,使用成熟的數據庫連接池,沒必要重複造輪子
使用單例,保證資料庫連線的唯一性
修改
synchronized
關鍵字的用法,提高效率增加
volatile
關鍵字,提高穩定性沒必要同步吧, 多個連線也沒關係啊。
資料庫自己有鎖的。
你也可以直接用連接池。
多謝大家的回答,我把程式碼改了一下,請大家幫我看看有沒有問題了,主要是沒做過java,我的處理方式就是:除了常數外,沒有類成員變量,全部用參數和回傳值傳遞,所有變數都在方法裡申明