我正在将Java程序连接到存储在program文件夹中的数据库,并且我让用户回答测验问题,并且希望将结果存储在数据库中。 Update语句不起作用,并且我不知道它是否与实际语句或数据库连接有关。
我尝试用相同的表创建一个新数据库并重新连接到该数据库,但是似乎没有任何作用。
//database connection class
public class databaseConnection {
public static Connection dbConnector() {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager
.getConnection("jdbc:sqlite:D:\\Users\\mariammahmoud\\eclipse-workspace\\ia_2019_final\\testjava.db");
return conn;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
public class student {
public static final String DB_NAME = "testjava.db";
public static final String TABLE_STUDENTS = "students";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_GRADE = "grade";
public static final String COLUMN_RESULTS = "results";
public static final String COLUMN_EVENTS = "events";
public static final String COLUMN_USERNAME = "username";
public void main() {
try {
String user_name = login_student.sendQuiz();
Connection conn = databaseConnection.dbConnector();
ArrayList<String> results = new ArrayList<String>(15);
instructions();
questions(results);
results.trimToSize();
System.out.println("Here are the events that you should consider competing in:");
System.out.println(results);
String separator = ",";
int total = results.size() * separator.length();
for (String finalResults : results) {
total += finalResults.length();
}
StringBuilder sb = new StringBuilder(total);
for (String finalResults : results) {
sb.append(separator).append(finalResults);
}
String resultsDatabase = sb.substring(separator.length());
String sql = "UPDATE students SET events = ? WHERE username = " +user_name;
PreparedStatement myStmt = conn.prepareStatement(sql);
myStmt.setString(1, resultsDatabase);
myStmt.executeUpdate();
} catch (SQLException e) {
System.out.println("Something went wrong:" + e.getMessage());
e.printStackTrace();
}
}
我期望update语句更新testjava.db数据库,但是一切都保持不变。我该怎么办?预先谢谢你!
答案 0 :(得分:2)
您的问题是,尽管您在代码中明智地使用了准备好的语句进行更新,但实际上从未在username
子句的WHERE
列中实际使用过该语句。因此,您当前正在执行的查询不会被解释为将某些输入与username
进行比较。相反,username
值将被解释为一列。试试这个版本:
String resultsDatabase = sb.substring(separator.length());
String sql = "UPDATE students SET events = ? WHERE username = ?";
PreparedStatement myStmt = conn.prepareStatement(sql);
myStmt.setString(1, resultsDatabase);
myStmt.setString(2, user_name);
myStmt.executeUpdate();
请注意,您可以刚刚尝试了以下操作:
String sql = "UPDATE students SET events = ? WHERE username = '" + user_name + "'";
但是,如上所述,请改为将值绑定到?
占位符。使用语句的好处之一是,它使您不必担心如何在查询中转义数据。