0

How do I use a PreparedStatement to pass a string in a where clause?

I have tried following lines of code:

String sql = "select pass from lbdb_user WHERE username = ? collate latin1_bin";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1,"\""+username+"\"" );

It throws the following mysql exception:

You have an error in your SQL syntax;

khelwood
  • 55,782
  • 14
  • 81
  • 108
parichay07
  • 45
  • 5
  • This has been asked many times before. Also, a simple google search will reveal how to do it. https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html – steven35 May 07 '19 at 14:03
  • Please provide a [mcve] (the code shown is incomplete) and the full exception stacktrace – Mark Rotteveel May 07 '19 at 14:28
  • 1
    It looks like you're trying to retrieve the password, which is already wrong. What you should be doing is `SELECT COUNT(*) FROM LBDB_USER WHERE USERNAME = ? AND PASS = ?`, supplying the username and password you were given, and seeing whether there was one or zero results. Let the database do the matching. All of it. – user207421 May 08 '19 at 09:16

2 Answers2

3

Try it like this:

String username = "Mickey Mouse";
String sql = "select pass from lbdb_user WHERE username = ? ";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, username);

I don't know what that collate thingy is. I would recommend using Unicode and UTF-8 in your database.

duffymo
  • 305,152
  • 44
  • 369
  • 561
0

Here is an example, using COLLATE latin1_bin, as what you have posted and it works

String lSql = "SELECT lastname FROM contacts WHERE lastname= ? COLLATE latin1_bin ";
PreparedStatement lPreparedStatement = con.prepareStatement(lSql);
lPreparedStatement.setString(1, "andre");
ResultSet lResultSet = lPreparedStatement.executeQuery();