简体   繁体   中英

MySQL 1064 syntax error when using statement

I am running a server that receives queries and sends them to the Database using Statements.

try{
    connection = dbConnection.getDbConnection();
    if(connection != null) {
         System.out.println("DA2");

        Statement mySt = connection.createStatement();
        if(mySt != null) {
           ResultSet myRs = mySt.executeQuery(query);
           System.out.println("DA3");

           while(myRs.next()){
               //getting data and printing it
           }
        }

}

It prints DA2 so the connection is created succefully. The query is send by the client in the following way

DataOutputStream out = new DataOutputStream(client.getOutputStream());
String query = "USE db_name; SELECT * FROM `tb_name`;";
out.writeUTF(query);

I changed the database name with db_name and the table name with tb_name(I am sure I wrote them correctly in my code).

The server receives them this way

Socket client = socket.accept();
DataInputStream input = new DataInputStream(client.getInputStream());
String query = input.readUTF();

When the server is running and the client sends the query an exception is thrown with the following message(I handled the exceptions to show me this).

SQLState: 42000 Error Code: 1064 Message: 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 'SELECT * FROM `tb_name`' at line 1

The same query runs correctly on a MySQL database.

How can I solve this? Is the database sending back the error and so throwing an exception or is it just the code?

SOLVED: I forgot to specify the database name in the connection.

您可以使用(具有限定名称的单个SQL语句):

String query = "SELECT * FROM db_name.`tb_name`";
public static Connection dbConnect() {
        Connection c = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            c = DriverManager.getConnection("jdbc:mysql://localhost:3306/DBNAME", "USERNAME", "PASSWORD");
        } catch (ClassNotFoundException e) {
            System.out.println("ClassNotFoundException " + e);
        } catch (SQLException e) {
            System.out.println("SQLException " + e);
        }
        return c;
    }

Hope you have created dbConnect in similar fashion. Here We heve included the database name in get connection method So explicitly no need to use database name for each time until you are accessing another database.

so your query should be

String query = "SELECT * FROM `tb_name`";

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