Reputation: 1721
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?
Upvotes: 4
Views: 42473
Reputation: 1013
ResultSet rs = stmd.executeQuery("select * from person where uid = "+ userid);
while (rs.next()) {
System.out.println("Name= " + rs.getString(1));
}
Upvotes: 5
Reputation: 1795
int user_id=2003; // you can also get input variable
String sql="SELECT * FROM employment WHERE id=";
resultSet = statement.executeQuery(sql+user_id);
Upvotes: -1
Reputation: 5064
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;
}
}
Upvotes: 9
Reputation: 398
Could you paste the whole code block about this question? Following is my suggestion
int userid = get user id ;
Connection connection = get connection ;
String sql = "select * from person where uid=?";
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setInt(1,userid);
if the database has one or more record which is uid filed equal the userid ,that will return the correct result
Upvotes: 5