SQL语法错误.....在第1行使用“7”附近

时间:2015-10-07 10:44:04

标签: java mysql

您的SQL语法有错误;

  

查看与您的MySQL服务器版本对应的手册,以便在第1行使用“7”附近的正确语法

我在以下代码中遇到上述错误,因此请建议我运行此代码的任何适当方法。 提前谢谢......

public void actionPerformed(ActionEvent ae)
{   
    String str1=(String)ae.getActionCommand();
    Object source = ae.getSource();
    if(source==home)
    {
        this.dispose();
        home t=new home();
        t.nn("","","","");
    }
    if(source==sh)
    {
        for(p=0;p<12;p++)
        {
            if(mo[p]==dob2.getSelectedItem())
            mo1=p+1;
            if(mo[p]==add2.getSelectedItem())
            mo2=p+1;
        }
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection c = DriverManager.getConnection("jdbc:mysql://localhost/billing", "root", "");
            Statement stm = c.createStatement();
            t=0;in=0;
            ResultSet rs = stm.executeQuery("select * from bill where (to_char(day,'mm') between "+mo1+" and "+mo2+")and(to_char(day,'dd') between "+dob1.getSelectedItem()+"and "+add1.getSelectedItem()+")");
            while(rs.next())
            {   
                t=1;    

                it[in]=rs.getInt("itid");
                ct[in++]=rs.getInt("count");
            }
            if(t==0)
            {
                jp.showMessageDialog(this,"Sorry, No Such Record exisits","INFORMATION",jp.ERROR_MESSAGE);
                t=0;
            }
                c.close();
            stm.close();
    }

3 个答案:

答案 0 :(得分:1)

我非常确定这是一个间距问题。修改您的查询,如

"select * 
from bill 
where to_char(day,'mm') between " + mo1 +" and " + mo2+ " and to_char(day,'dd') between " +dob1.getSelectedItem()+ " and   "+add1.getSelectedItem()+"

答案 1 :(得分:1)

使用准备好的陈述而不是陈述。这可以避免空间问题,引用问题等。此外,它会阻止您从SQL注入漏洞。

问题是sql语句中参数之间的空格,如下所示:

ResultSet rs = stm.executeQuery("select * from bill where (to_char(day,'mm') between "+mo1+" and "+mo2+")and(to_char(day,'dd') between "+dob1.getSelectedItem()+"and "+add1.getSelectedItem()+")")

应该是

ResultSet rs = stm.executeQuery("select * from bill where (to_char(day,'mm') between "+mo1+" and "+mo2+")and(to_char(day,'dd') between "+dob1.getSelectedItem()+" and "+add1.getSelectedItem()+")")

答案 2 :(得分:0)

你的上一个“和[...]”有间距问题。应该是“和[...]”

另外,我可能在这里错了,但你不是在混淆Oracle的to_char()和MySQL的date_format()函数吗?

在Oracle中,MySQL中的to_char(day,'mm')应为date_format(day,'%m')

SELECT DATE_FORMAT(SYSDATE(), '%m');
Result: 10

http://www.sqlines.com/oracle-to-mysql/to_char_datetime