Search code examples
javamysqlresultset

Using java variables in Mysql where clause


I wanted to use java variables in SQL syntax.Please suggest whether its possible or not.Here is my code

String Userid_input=request.getParameter("Userid");//I am getting dynamic input from User

String Password_input=request.getParameter("Password");

The database connection is being given below

Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/Proj_name","root","root");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select User_type from Signup where User_name.User_name=Userid_input");//**Userid_input** is a java variable

I am getting the following error ,

Exception occured com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Unknown column 'Userid_input' in 'where clause'


Solution

  • Try this,

       String query = "select User_type from Signup where User_name.User_name="+Userid_input;
       ResultSet rs = st.executeQuery(query);
    

    Reference : https://docs.oracle.com/javase/tutorial/jdbc/basics/retrieving.html