java - java.sql.SQLSyntaxErrorException:您的 SQL 语法有错误;通过JAVA向SQL数据库插入数据时
问题描述
我正在设计一个 JFrame,我将在其中接受来自 JFileChooser 的名称、用户名、密码、电话、号码和图像位置“img”的数据。不切实际,我插入的密码没有散列,电话号码列的数据类型为 VarChar(45)。这应该被忽略,因为我对使用 JAVA 的 SQL 编程很陌生。
注册按钮用于将数据插入 SQL 行。ActionListener 如下:
signupbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try
{
Statement st=conn.createStatement();
ResultSet rs=null;
String name=namef.getText(),usnm=usnmf.getText(),pswd=pswdf.getText(),ph=phf.getText();
String sql="insert into data (name,username,password,ph.no.,profile) values("+name+","+usnm+","+pswd+","+ph+","+img+")";
st.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
int key = 0;
rs = st.getGeneratedKeys();
if (rs.next())
{
key = rs.getInt(1);
}
JOptionPane.showMessageDialog(null, "Key : "+key);
}
catch(Exception ex)
{
System.out.println(ex);
}
}
});
当给出数据并单击按钮时,会捕获并打印异常:
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ',profile) values(Jyotirmay,Usnm,Pswd,1122334455,E:\1.jpg' at line 1
为什么会出现错误?我尝试了几种方法,例如使用PreparedStatement
而不是Statement
使用,?
但仍然出现错误。
附言
使用 PreparedStatement:
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try
{
String sql="INSERT into data (name, username, password, ph.no., profile) VALUES (?,?,?,?,?);";
PreparedStatement st=conn.prepareStatement(sql);
String name=namef.getText(),usnm=usnmf.getText(),pswd=pswdf.getText(),ph=phf.getText();
st.setString(1, name);
st.setString(2, usnm);
st.setString(3, pswd);
st.setString(4, ph);
st.setString(5, img);
st.executeUpdate();
JOptionPane.showMessageDialog(null, "SUCESS! Data inserted. Try Logging In.");
}
catch(Exception ex)
{
System.out.println(ex);
}
}
});
注意: img 已经声明并初始化。此外,在控制台中正确打印了 asolute 图像位置。
解决方案
您不能在不转义的情况下在列名中使用点。最好重命名该列,使其不再使用点,尽管您也可以尝试在列名中使用反引号,如下所示:
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try
{
String sql="INSERT into data (name, username, password, `ph.no.`, profile) VALUES (?,?,?,?,?);";
PreparedStatement st=conn.prepareStatement(sql);
String name=namef.getText(),usnm=usnmf.getText(),pswd=pswdf.getText(),ph=phf.getText();
st.setString(1, name);
st.setString(2, usnm);
st.setString(3, pswd);
st.setString(4, ph);
st.setString(5, img);
st.executeUpdate();
JOptionPane.showMessageDialog(null, "SUCESS! Data inserted. Try Logging In.");
}
catch(Exception ex)
{
System.out.println(ex);
}
}
});
推荐阅读
- r - 如何修复“grouped_df_impl(data, unname(vars), drop) 中的错误:列 `...` 未知”。在函数中使用管道、group_by 和汇总
- python - 如何使用 ruamel.yaml 添加评论
- wpf - 在 WPF 的 WrapPanel 中的 LiveCharts 的情况下,它不能垂直滚动,
- amazon-web-services - 使用隧道 EC2 通过 SSH 将 Tableau 最终用户连接到 AWS RDS Aurora
- git - 多个开发人员在一个功能分支上提交
- r - 为什么通过网格搜索调整后随机森林仍然过拟合?
- javascript - 删除 chart.js 条形图中的删除线行为
- c# - 如何将ASCII码发送到串口c#
- chart.js - 我的堆叠条形图中未使用我选择的颜色
- laravel - 来自 API 回调的 Laravel 5.8 会话丢失