连接java并使用“'”时出现SQL语法错误

时间:2014-11-02 16:14:49

标签: java sql ms-access jdbc-odbc

我已经使用java applet连接了一个访问数据库。在这里,我在学校工作时给予学生和学校的价值,有两所学校(假设):

小花学校 圣约瑟夫学校

我有一个方法存储和getchestname(它用于校际比赛。将胸部名称作为唯一ID)。这两个函数都运行sql命令,如下所示:

//getchestname :

        ResultSet rs = db.exec("SELECT * FROM Pariticipants WHERE `school` = '"+schools[sc][1]+"' AND event = '"+events[ev][1]+"' AND category = '"+cat[ca][1]+"' AND gender = '"+g2+"'");

//Store:

    rs = db.exec("INSERT INTO Pariticipants ( school , name, event, category , gender ,chestname ) VALUES  ('"+schools[sc][1]+"','"+name+"','"+events[ev][1]+"','"+cat[ca][1]+"','"+g+"','"+cname+"')");

当学校设置为小花学校时,它可以很好地工作,但是当我使用后者时,它会出现这个错误:

java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error (missing operator) in query expression '`school` = 'St. Joseph\'s school' AND event = '50 m Race' AND category = 'Primary' AND gender = 'Boy''.

我认为这是由于撇号(')。

修改: DBConn.java(数据库连接。早期)

import java.sql.*;

/**
 * Write a description of class DBConnector here.
 * 
 * @author Darshan Baid
 * @version (a version number or a date)
 */
public class DBConn
    {
        String accessFileName = "C:\\Users\\Darshan\\Documents\\Database1.accdb";
        Connection con;
        public ResultSet exec(String query)
        {
            try{
                Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);

                stmt.execute(query); // execute query in table student

                ResultSet rs = stmt.getResultSet(); // get any Result that came from our query
                return rs;
            }
            catch(Exception e)
            { 
                e.printStackTrace(); 
                return null;
            }
        }
        public void connect() {

            try {

                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

                String connURL="jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="+this.accessFileName+";";

                this.con = DriverManager.getConnection(connURL, "","");

            }
            catch(Exception e)
            { 
                e.printStackTrace(); 
            }
        }
        public boolean close()
        {
            try{
                con.close();
                return true;
            }

            catch(Exception e)
            { 
                e.printStackTrace(); 
                return false;
            }
        }

    }

现在:

import java.sql.*;

public class DBConn
    {
        String accessFileName = "C:\\Users\\Darshan\\Documents\\Database1.accdb";
        Connection con;
        public ResultSet exec(String query)
        {
            try{
                Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);

                stmt.execute(query); // execute query in table student

                ResultSet rs = stmt.getResultSet(); // get any Result that came from our query
                return rs;
            }
            catch(Exception e)
            { 
                e.printStackTrace(); 
                return null;
            }
        }
        public ResultSet exec(String query,String[] ar)
        {
            try{
                PreparedStatement userRecord_stmt = con.prepareStatement(query);

                for(int i = 0; i< ar.length;i++)
                    userRecord_stmt.setString(1,ar[i]);

                    ResultSet userRecord_rs = userRecord_stmt.executeQuery();

                    return userRecord_rs;


            }catch(Exception e)
            {
                e.printStackTrace();
                return null;
            }
        }
        public void connect() {

            try {

                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

                String connURL="jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="+this.accessFileName+";";

                this.con = DriverManager.getConnection(connURL, "","");

            }
            catch(Exception e)
            { 
                e.printStackTrace(); 
            }
        }
        public boolean close()
        {
            try{
                con.close();
                return true;
            }

            catch(Exception e)
            { 
                e.printStackTrace(); 
                return false;
            }
        }
    }

改变胸部名称。 :

    String ar[] = {schools[sc][1],events[ev][1],cat[ca][1],g2};
    //ResultSet rs = db.exec("SELECT * FROM Pariticipants WHERE `school` = '"+schools[sc][1]+"' AND event = '"+events[ev][1]+"' AND category = '"+cat[ca][1]+"' AND gender = '"+g2+"'");
    ResultSet rs = db.exec("SELECT * FROM Pariticipants WHERE `school` = ? AND `event` = ? AND `category` = ? AND `gender` = ?",ar);

面临的错误:

java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver]COUNT field incorrect

2 个答案:

答案 0 :(得分:3)

不要通过连接值来创建SQL个查询。在您的情况下,您正面临SQL注入。您的值具有'使用的特殊字符Access。避免这种做法。相反,请使用PreparedStatement

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo", "root", "root");
PreparedStatement userRecord_stmt = con.prepareStatement("SELECT * FROM Pariticipants WHERE `school` = ? AND event = ? AND category = ? AND gender = ?");
userRecord_stmt.setString(1,schools[sc][1]);
userRecord_stmt.setString(1,events[ev][1]);
userRecord_stmt.setString(1,cat[ca][1]);
userRecord_stmt.setString(1,g2);
ResultSet userRecord_rs = userRecord_stmt.executeQuery();

我不确定您的DataType表格,因此我在每种情况下都使用了setString

答案 1 :(得分:0)

我可能会对此提出批评,但我使用函数q()自动引用字符串。它就像参数化所有东西一样安全,而且对于快速和肮脏的东西来说更加清洁。

rs = db.exec("INSERT INTO Pariticipants ( school , name, event, category , gender ,chestname ) 
VALUES  (" + q(schools[sc][1]) + "," + q(name) + "," + q(events[ev][1]) 
 + ","+ q(cat[ca][1]) + "," + q(g) + "," + q(cname) + ")");


Public Function q(i As Variant) As String
    q = QuoteWithEscape(i, "'")
End Function

Public Function QuoteWithEscape(i As Variant, QuoteChar As String) As String
    If QuoteChar = "" Then
        QuoteWithEscape = CStr(i)
        Exit Function
    End If

    If IsNull(i) Then
        QuoteWithEscape = QuoteChar & QuoteChar
    Else
        If InStr(i, QuoteChar) = 0 Then
            QuoteWithEscape = QuoteChar & i & QuoteChar
        Else
            QuoteWithEscape = QuoteChar & Replace(CStr(i), QuoteChar, QuoteChar & QuoteChar, , vbTextCompare) & QuoteChar
        End If
    End If
End Function