我仍然无法找出为什么我的SQL语句无法在我的JAVA程序上运行,但它们在Workbench上运行!
我正在尝试创建一个用户可以注册或登录的界面。 要注册,我有这个错误:
严重:空 com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:'字段列表'中的未知列'Admin'
我在工作台上可以看到数据库上的用户名“Admin”
此外,如果我单击Clear按钮,然后键入OK,它不会给出注册错误,我可以看到我的数据表,因为它跳过了尝试注册代码的部分,因为字符串是空的并运行else块;
(MyUserApp类代码)
private void RegisterButtonActionPerformed(java.awt.event.ActionEvent evt) {
String username, password, address, dob;
try {
// TODO Register very important too!
username = newUsernameField.getText();
password = passwordField2.getText();
address = addressField.getText();
dob = dateofbField.getText();
if( username == null || password == null || username.isEmpty() || password.isEmpty() || password.length() < 6 )
jLabel6.setText("The information you typed in is not valid. ");
else{
this.app.registerUser(app, username, password, dob, address);
}
String u = this.app.showDB(app);
showTableDB.setText(u);
} catch (SQLException ex) {
Logger.getLogger(UserAppUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
(UI类代码)
public void registerUser(MyUserApp app, String username, String pw, String dob, String address) throws SQLException{
String sb = "INSERT INTO javabase.user (iduser, username, password, date_of_birth, address)\n VALUES (" + app.incID()+", "+username+", "+pw+", "+dob+", "+address +");";
PreparedStatement statement = app.getCon().prepareStatement(sb);
statement.execute();
}
当我尝试登录时会发生这种情况 https://prnt.sc/gajpns
当我尝试注册时会发生这种情况: https://prnt.sc/gak3uh
使用户登录的代码基本上是这样的:
this.app.login(this.app, username, pw);
在UI类上的,调用这个:
public void login(MyUserApp app, String user, String pw) throws SQLException{
String sql = "SELECT * FROM javabase.user WHERE username = "+ user +" and password = "+pw+";";
PreparedStatement statement = app.getCon().prepareStatement(sql);
statement.execute();
}
答案 0 :(得分:0)
您必须在mysql中用单引号或双引号括起字符串文字,例如用户的名字或密码。如果不这样做,那么mysql会将它们解析为列名。
String sql = "SELECT * FROM javabase.user WHERE username = '"+ user +"' and password = '"+pw+"';";
您必须根据我上面提供的解决方案编辑所有其他语句。
但是,请考虑Gordon的建议并使用参数而不是字符串连接。
答案 1 :(得分:-2)
我使用了SQL参数
public boolean registerUser(MyUserApp app, String username, String pw, String dob, String address) throws SQLException{
String sb = "INSERT INTO user (iduser, username, password, date_of_birth, address)\n VALUES ( ?, ?, ?, ?, ?);";
PreparedStatement statement = app.getCon().prepareStatement(sb);
statement.setInt(1, app.incID());
statement.setString(2, username);
statement.setString(3, cryptWithMD5(pw));
statement.setString(4,dob);
statement.setString(5,address);
boolean status = statement.execute();
return status;
}