简体   繁体   中英

Cannot insert into database with prepared statements

I'm trying to enter into a table called services, and it has an id, service_name and service_type. I get an error when I try to run it.

public void insertService(String service, String serviceType) {

    try {
        st = myConn.createStatement();
        String query = "INSERT INTO services"
                         +"(service_name, service_type)"
                         +"values(?,?)";
        PreparedStatement preparedStmt = myConn.prepareStatement(query);
        preparedStmt.setString(1, service);
        preparedStmt.setString(2, serviceType);

        st.executeUpdate(query);
    } catch(Exception e) {
        System.out.println("Cannot Add service" + e);
    }

}

myConn does not appear to be defined.

Connection myConn = DriverManager.getConnection(url,user, password);

EDIT 1

Maybe because you're executing the query without the values?

st.executeUpdate(query); versus preparedStmt.executeUpdate()

EDIT 2

myConn does not appear to be defined.

Connection myConn = DriverManager.getConnection(url,user, password);

Ignore this bit. The answer was in the first edit.

You are missing spaces in your query in several places. Try:

String query = "INSERT INTO services "
                         +"(service_name, service_type) "
                         +"values(?,?)";

It is always recommended to run your query manually before putting it in your code to verify it is syntactically correct/valid.

As you mentioned the error is MySQLSyntaxErrorException. You should be looking your sql query generated.

Use below query

String query = "INSERT INTO services "
                         +"(service_name, service_type) "
                         +"values(?,?)";

An space before double quote of every line

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