I want to write a select ... where... mysql query in my java program (using jdbc). but the problem is that in where section i m gonna refer to a string variable. but i don know if it is possible?
here is the mentioned query for select where:
String select = "Select name,manfac,Qmax,Qmin,Qw,Pmax,Pmin,Pw,deadline,Tw"+" from tseller where name = 'targetName' order by Pmax";
but actually tagetName is a string variable. how should i write that?
I try to use prepared statements, but the examples i find are mostly using oracle but im working with MYSQL. any way i've tried this code. unfortunately it is not working! i think it can not fetch information from table in mysql. Do you have any idea what can i do?
here is my code:
You'll need a Statement instance, and call executeQuery on that instance.
Joined: Jul 06, 2009
I run this code:
Connection con= DriverManager.getConnection("jdbc:mysql://localhost/booktrading?"+"user=root&password=444");
StringBuilder query = new StringBuilder() ;
String targetGood = "Celeron";
query.append("select * from tseller where name=").append(targetGood).append(" order by Pmax");
Statement s = con.createStatement();
ResultSet rows = s.executeQuery(sahar);
and it throws this error:
SQLException: Unknown column 'Celeron' in 'where clause'
As i find this error is related to an un exist column.(as you can see in query) name refers to name as column!(which is actually exist!!) I dont know how it jumps suddenly to targetGood without reading name?
Joined: Feb 12, 2009
if you don't use parameters for your query you have to put your String into quotation marks. If not the DB thinks the value (in your case Celeron) is a column name.
But as Rob already mentioned you should prefer using parameters as you did in your first attempt.