MySQL语法错误异常

时间:2015-11-04 20:03:44

标签: java mysql jdbc

我在这里无法执行查询。它说上面提到的错误。我尝试过从客户那里选择*。查询,它正在工作。我无法弄清楚我哪里出错了。请提前帮助和谢谢。

完整查询是 - SELECT CUSTOMER_ID,FIRST_NAME,LAST_NAME,COUNTRY,AGE,GENDER,来自客户的EMAIL_ADDRESS FIRST_NAME =' SHIVAM';

错误消息是-com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErr或异常:未知的颜色' SHIVAM'在' where子句'

DefaultTableModel model;
model=(DefaultTableModel)tblSearchCustomer.getModel();
try{
 Class.forName("java.sql.Driver");
 Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/divign","root","password");
 Statement stmt=con.createStatement();

 String sfld=(String) searchfldCB.getSelectedItem();
//this stands for Search Field(ComboBox)
 String op=(String) opCB.getSelectedItem();
//this stands for operator(ComboBox) 
 String crit=criteriaTF.getText();
 //this stands for criteria
 String query="SELECT CUSTOMER_ID,FIRST_NAME,LAST_NAME,COUNTRY,AGE,GENDER,EMAIL_ADDRESS FROM CUSTOMER WHERE" + sfld+""+op+""+crit+" ;";
 //This Query is not Executing
 ResultSet rs=stmt.executeQuery(query);
 while(rs.next()) {
     model.addRow (new Object[ ] {

       rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getInt(5),
       rs.getString(6),rs.getInt(7)
     } );

 }
rs.close();
stmt.close();
con.close();
 }
catch(Exception e){   
JOptionPane.showMessageDialog(null,e.toString());
}

3 个答案:

答案 0 :(得分:2)

当您生成查询时,where语句中没有单引号,这意味着您将获得WHERE FIRST_NAME=SHIVAM,因此它会尝试将first_name与名为SHIVAM的列进行比较,而该列并不是存在

答案 1 :(得分:1)

所以这是更正的查询 -

字符串查询=" SELECT CUSTOMER_ID,FIRST_NAME,LAST_NAME,PASSWORD,ADDRESS,COUNTRY,AGE,GENDER,EMAIL_ADDRESS,PHONE_NUMBER FROM CUSTOMER WHERE" + sfld的+" &#34 + + OP" '&#34 + +暴"' ;&#34 ;;

注意暴击周围的引号....现在,如果我在jTextField(criteriaTF)中键入SHIVAM,那么名称将在MySQL中用引号执行,即' SHIVAM'

答案 2 :(得分:0)

字符串查询=" SELECT CUSTOMER_ID,FIRST_NAME,LAST_NAME,COUNTRY,AGE,GENDER,EMAIL_ADDRESS FROM CUSTOMER WHERE" + sfld +"" + op +"" + crit +" ;&#34 ;;

在where条件中,您还没有提到列名称来指定sfld的值+"" + op +"" + crit。

您必须在where子句旁边提供列名。