【发布时间】:2014-03-09 05:07:14
【问题描述】:
您好,我正在为一个学校项目开发应用程序,我想创建一个将保存在数据库中的用户。
我已经创建了一个 Profile 类
public class Profile{
private String username;
private String password;
public Profile(String _username, String _password){
this.username = _username;
this.password = _password;
}
public void setUsername(String username){
this.username = username;
}
public String getUsername(){
return this.username;
}
public void setPassword(String _password){
this.password = _password;
}
public String getPassword(){
return this.password;
}
我创建了一个 DBConnect 类,其中包含所有方法,其中之一是 CreateProfile,我希望用户将新配置文件的值插入到数据库“用户”表中。
public class DBConnect {
private Connection dbConnection;
public DBConnect(){
try{
dbConnection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?user=root");
}catch(Exception ex){
System.out.println("Connection failed :" +ex);
}
}
public void createProfile(Profile profile){
Statement stm = null;
try{
stm = dbConnection.createStatement();
stm.executeUpdate("INSERT INTO User (Username,Password) VALUES (\"" + profile.getUsername() + "\", \"" + profile.getPassword()+ "\"");
}catch(SQLException ex){
System.out.println(ex);
}
}
最后,在我的 JFrame 中,我有两个 textFeilds 用户名和密码,我想使用它们来传递配置文件构造函数的参数。完成此操作后,我将使用 DBConnect 对象开始连接,然后调用在 DBConnect 中声明的 Create Profile 方法。
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Profile p = new Profile(jTextField1.getText(), jPasswordField1.getText());
DBConnect dbc = new DBConnect();
dbc.createProfile(p);
一切都可以编译,但是当我运行程序并尝试创建一个新的配置文件时,我得到了这个错误。
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 你的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的 '' 附近使用正确的语法
我的 MySQL 表是一个简单的表,有两列分别称为“用户名”和“密码”
【问题讨论】:
-
忘记
Statement,使用PreparedStatement。