Connecting to MySQL using Java on Debian

I am trying to connect to MySQL database with Java and I get the following error:

SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '????????????????' at line 1

I cannot understand the error and searched a lot on the web but did not found anything. This is the code I am using:

    try
    {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
    }
    catch (Exception E)
    {
        System.err.println("Unable to load driver");
        E.printStackTrace();
    }

    try
    {
        Connection C = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/DATABASE_NAME","USERNAME","PASSWORD");
        Statement Stmt = C.createStatement();

        ResultSet RS = Stmt.executeQuery("SELECT somefield FROM sometable");

        while (RS.next())
        {
             System.out.print("\"" + RS.getString(1) + "\"");
             System.out.print(" by " + RS.getString(2));
             System.out.println(": " + RS.getString(3));
        }
        C.close();
        RS.close();
        Stmt.close();
    }
    catch (SQLException E)
    {
        System.out.println("SQLException: " + E.getMessage());
        System.out.println("SQLState:     " + E.getSQLState());
        System.out.println("VendorError:  " + E.getErrorCode());
    }

The SQL query above is an example for the question. The one I am using works without any problem in MySQL console. In fact, even if I remove the query and the statement from the code above, I still get the same error. Can someone help? Thanks in advance

Upvotes: 0

Views: 555

Answers (1)

Steven Fines
Steven Fines

Reputation: 477

Most likely it's because you're using select field from table- table is a SQL reserved word. If you want to do this query, you'll probably need to do

select field from `table` 

with the word table in back ticks.

Upvotes: 3

Related Questions