简体   繁体   中英

can not insert datum using preparestatement

I am trying to insert datum into mysql database using prepareStatement but its shows error like

Type mismatch: cannot convert from java.sql.PreparedStatement to com.mysql.jdbc.PreparedStatement

Below is my code:

<%@ page import="java.sql.*" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>


           <%

               try
                   {
                      Class.forName("com.mysql.jdbc.Driver");
   Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");
                      // Statement st=connection.createStatement();
                      PreparedStatement st=null;
                      String Eid = request.getParameter("Eid");
                      String Rpswd=request.getParameter("Rpswd");
                      String uType=request.getParameter("uType");

                     // String query="insert into login_table(`uid`,`pswd`,`user_type`)  values('"+Eid+"','"+Rpswd+"','"+uType+"')";
    String query="insert into login_table(`uid`,`pswd`,`user_type`)  values(?,?,?)";
                       st = con.prepareStatement(query);
                       st.setString(1,Eid);
                       st.setString(2,Rpswd);
                       st.setString(3,uType);


                           // int i= st.executeUpdate(query);

                         int i= st.executeUpdate();


                      }
                 catch(Exception e)
                              {
                                 e.printStackTrace();
                               }

                   %>

</body>
</html>

Which is getting the error on st = con.prepareStatement(query); .

Help me. Where am I wrong?

Note : This the first time I am using preparedstatement from CreateStatement so suggest me which one is good for code?.

Fix your imports and replace

import com.mysql.jdbc.PreparedStatement;

by

import java.sql.PreparedStatement;

You should never use mysql-specific classes in your code. The standard JDBC classes are all you need.

Regarding the use aof prepared stataments, yes, it should be used every time you need to pass parameters to a query. It's a matter of robustness and of security (read about SQL injection attacks).

But JDBC code, and scriptlets in general, have nothing to do in JSPs. JSPs are view components, whose job is to generate HTML. They're not data access components. These should be written in Java and accessed from a controller servlet.

Just remove

import com.mysql.jdbc.PreparedStatement;

and replace with

import java.sql.PreparedStatement;

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