简体   繁体   中英

I am stuck I cannot insert data into MySQL database from JDBC

I want to do simple signup form, but I cannot go forward, i have tried everything and it still does not work this is my code:

protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException
    {
        StringBuilder builder= new StringBuilder();
        Reader reader=request.getReader();
        int c;
        while ((c=reader.read())!=-1)
        {
            builder.append((char) c);
        }
        String signup=builder.toString();
        try {
            JSONObject object= new JSONObject(signup);
            String name=object.getString("username");
            String email=object.getString("email");
            String pass=object.getString("pass");
            String sql="INSERT INTO user_f VALUES("+email+","+name+","+pass+")"+";";

            statement.executeUpdate(sql);
            //ResultSet set= statement.executeQuery("SELECT ")

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

My Error Stack I edited the code so many times and I am kinda getting frustrated this the error that I am getting :

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 '@gmail.com,dsf,sdfsd)' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
    at com.mysql.jdbc.Util.getInstance(Util.java:387)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:939)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3878)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3814)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2478)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2625)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2547)
    at com.mysql.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1541)
    at com.mysql.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2605)
    at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1469)
    at com.herda.app.Servlet.doPost(Servlet.java:56)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

Your MySQL query does not have a valid syntax as the error is saying. You need quotes around string literals. Try something like this:

String sql = "INSERT INTO user_f VALUES(\"" + email + "\", \"" + name + "\", \"" + pass + "\");";

However, be aware that this code is open to SQL injections! To resolve this security issue, you can use prepared statements. That also resolves the quote problem for you.

You shoud test your sql query fist. execute it on MySql Workbench

I think it should be

String sql="INSERT INTO user_f VALUES('"+email+"','"+name+"','"+pass+"')"+";";

The problem is you are missing quotes around your values, however you should never construct queries like this by concatenating values in to the query string. It opens your code to SQL injection (eg when you are inserting user input), which is a very big security risk. Instead you should use a prepared statement with parameter placeholders. This will take care of escaping values so SQL injection won't be a problem.

Prepared statements on some database systems also have the added value of leading to better performance because the statement can be reused.

As an example:

try (PreparedStatement pstmt = connection.prepareStatement(
           "INSERT INTO user_f(email,name,pass) VALUES(?,?,?)")) {
    pstmt.setString(1, email);
    pstmt.setString(2, name);
    pstmt.setString(3, pass);
    pstmt.executeUpdate();
}

In this answer I have also explicitly listed the columns you are inserting, this makes your code more future proof (for example when you add or remove columns).

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