我想将我的游戏的高分保存到数据库而不是 .dat 文件,并且希望是否有人可以帮助我如何做到这一点。
我已经为数据库创建了类,我只是不确定如何实现将高分保存在数据库中。
public class ScoreDB {
Connection conn = null;
String url = "jdbc:derby:ScoresDB;create=true";
String username = "hello";
String pass = "hello";
public void connectScoreDB(){
try{
conn= DriverManager.getConnection(url,username,pass);
}catch(SQLException ex){
System.err.println("SQLException: " + ex.getMessage());
}
}
最佳答案
你可以按照下面的方式做
public void Add(int highScore) throws SQLException {
String query = "INSERT INTO ScoresDB VALUES(highScore)";
try (Statement stmt = getConn().createStatement()) {
stmt.executeUpdate(query);
}
}
我不知道你的表中有多少字段,但如果你想在一般情况下使用 INSERT 命令,你应该遵循这个
INSERT INTO table_name VALUES (value1,value2,value3,...);
注意:你的ScoresDB有一个是high score的字段
第二种方式是使用PreparedStatement
例如:
public void Add(int highScore){
String sql = "INSERT INTO ScoresDB (highScore) VALUES (?)";
try (PreparedStatement ps = getConn().prepareCall(sql)) {
ps.setString(1, highScore);
ps.executeUpdate();
}
}
要了解 using statement 和 preparedstatement 之间的区别,您还应该查看此链接。 Difference between Statement and PreparedStatement
关于java - 在 Java JDBC 中将高分保存到数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23859540/