简体   繁体   中英

SQL syntax error when connecting with java and using “ ' ”

I have connected an access db with java applet. In it I am giving values of students and their schools when working with schools, there are two schools (supposingly):

Little Flower School
St. Joseph's School

I have a method store and getchestname (it is for an inter-school contest. go the chest name as an unique id). Both the functions run sql commands as follows:

//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+"')");

When the school is set to Little Flower School, it works perfectly but when I am working with the later one, it gives this error :

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''.

I think it is due to apostrophe (').

DBConn.java(db connection . earlier) 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;
            }
        }

    }

Now:

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;
            }
        }
    }

And changes to chestname func. :

    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);

error faced:

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

Don't create SQL queries by concatenating values. In your case you are facing SQL injection. Your value has special character ' used by Access . Avoid this practice. Instead, use a 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();

I'm not sure about your DataType of table so I used setString in every case.

I'll probably attract criticism with this, but I use a function q() to quote strings automatically. It is just as safe as parameterizing everything and a hell of a lot cleaner for quick and dirty stuff.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM