我有
public HashMap<Integer, String> data;
private void initData() {
data= new HashMap<Integer, String>();
data.put(1, "One");
data.put(2, "Two");
data.put(3, "Three");
data.put(4, "Four");
data.put(5, "Five");
}
但是数据不断增加,所以我想将这个 HashMap 移到数据库中,所以每当我添加新的键值对时;我可以将它添加到数据库而不是接触java代码。
如何做到这一点? 创建表, hibernate ,连接它......但对创建表和数据库调用感到困惑
最佳答案
数据库连接器
import java.sql.*;
public class Database {
private static final String JDBC_DRIVER = "org.postgresql.Driver";
private static final String URL = "jdbc:postgresql://localhost/testdb";
private static final String USERNAME = "root";
private static final String PASSWORD = "pass";
private static Connection conn = null;
public Database() {
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("Database Connection Initialized.");
}
public void closeConnection() {
if (conn == null) return;
try {
conn.close();
conn = null;
} catch(SQLException ex) {
ex.printStackTrace();
}
}
public boolean execute(String sql) throws SQLException {
if (conn == null)
throw new SQLException("Connection null!");
Statement statement = conn.createStatement();
boolean res = statement.execute(sql);
statement.close();
return res;
}
public int executeUpdate(String sql) throws SQLException {
if (conn == null)
throw new SQLException("Connection null!");
Statement statement = conn.createStatement();
int res = statement.executeUpdate(sql);
statement.close();
return res;
}
public ResultSet executeQuery(String sql) throws SQLException {
if (conn == null)
throw new SQLException("Connection null!");
Statement statement = conn.createStatement();
ResultSet res = statement.executeQuery(sql);
statement.close();
return res;
}
}
创建表
Database db = new Database();
String sql = "CREATE TABLE IF NOT EXISTS `table` ("+
"`key` INT(6) PRIMARY KEY,"+
"`value` VARCHAR(50) NOT NULL"+
");";
db.execute(sql);
db.closeConnection();
将数据放入数据库
Database db = new Database();
for (Entry<Integer, String> next : hashMap) {
db.executeUpdate("INSERT INTO table (Key, Value) VALUES("+next.getKey()+",'"+next.getValue()+"');";
}
db.closeConnection();
从数据库中提取数据
Database db = new Database();
ResultSet resSet = db.executeQuery("SELECT * FROM table");
while (resSet.next()) {
hashMap.put(resSet.getInt("Key"), resSet.getString("Value"));
}
resSet.close();
db.closeConnection();
关于java - 将 Hashmap 数据移至数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32234725/