Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a SQL statement with a variable as WHERE?

Tags:

java

sql

jdbc

I have some Java code like

int userid = take user input;

And then execute following sql statement,

        Class.forName(dbdriver);
        conn = DriverManager.getConnection(url, username, password);
        st = conn.createStatement();

        st.executeUpdate("select * from person where uid = userid" );

Now, I don't know the returned result is null. I think where uid = userid is giving wrong result because it is searching for literal uid value "userid". Actually, I want to retrive information from person table about user provided uid values. Can anybody help me how to solve this?

like image 974
alessandro Avatar asked Dec 03 '22 05:12

alessandro


1 Answers

You should use prepare statement as it protect you from sql injection. You can also add a simple logging by printing out the sql statement before it is executed and so you are sure. Below is the example class but feel free to change it in your situation.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;


public class DBAccess
{
    PreparedStatement pstmt;
    Connection con;

    DBAccess() throws Exception
    {
        String dbdriver = "";
        String url = "";
        String username = "";
        String password = "";

        Class.forName(dbdriver);

        con = DriverManager.getConnection(url, username, password);
    }

    public Person getPerson(int userid) throws Exception
    {
        pstmt = con.prepareStatement("select * from person where uid = ?");
        pstmt.setInt(1, userid);
        System.out.println("sql query " + pstmt.toString());
        ResultSet rs = pstmt.executeQuery();
        if (rs.next())
        {
            Person person = new Person();
            person.setName(rs.getString("name"));
            return person;

        }
        return null;        
    }

}
like image 116
Jasonw Avatar answered Dec 09 '22 16:12

Jasonw