gpt4 book ai didi

java - 将 Hashmap 数据移至数据库

转载 作者:行者123 更新时间:2023-12-01 11:12:01 24 4
gpt4 key购买 nike

我有

  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 ,连接它......但对创建表和数据库调用感到困惑

最佳答案

数据库连接器

JDBC DRIVER

    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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com