-1

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

Edit: DBConn.java(db connection . earlier)

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

halfer
  • 19,824
  • 17
  • 99
  • 186
frunkad
  • 2,433
  • 1
  • 23
  • 35

2 Answers2

3

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Vicky Thakor
  • 3,847
  • 7
  • 42
  • 67
  • i am new to sql with java.. i have my db connection as follows : `Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String connURL="jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="+this.accessFileName+";";` and sql execution `Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY); stmt.execute(query); // execute query in table student ResultSet rs = stmt.getResultSet();` what changes shall i do – frunkad Nov 02 '14 at 16:20
  • will changing Statement to PreparedStatement be helpful – frunkad Nov 02 '14 at 16:22
  • @DarshanJain Yeah `PreparedStatement` is the best practice. And don't paste your code in comment just edit your question. – Vicky Thakor Nov 02 '14 at 16:24
  • i just changed it to PreparedStatement but now , when i run main func of the app it show nothing.. wait, i am editing the ques – frunkad Nov 02 '14 at 16:26
  • You need to set values in `stmt` `[PreparedStatement]` like i used. – Vicky Thakor Nov 02 '14 at 16:30
  • Now i am facing this error: `java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver]COUNT field incorrect` – frunkad Nov 02 '14 at 16:47
0

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
Ben McIntyre
  • 1,972
  • 17
  • 28