I have a problem with a SQL Command.
I have a string that holds a SQL command, but when I run, it returns me an error: Column n1 does not exist Note: n1 is what I typed in my textField.
Code:
String nameprod tf_NameProd.getText = ();
String sql = "select * from Product where prod_name =" + nameprod;//<-- this is my query
iaeprod.Table(sql, tbl_Prod);
Any idea where I am missing?
You need to put single quotes around the string in your SQL. For example in your case it should be
"select * from Product where prod_name = '" + nameprod + "'";
String sql = "select * from Product where prod_name = '" + nameprod + "'";
because prod_name is a String use single quotes around the value
String sql = "select * from Product where prod_name ='" + nameprod+"'";
it will better to use prepared statement
Use this method instead:
Connection dbConnection = getDBConnection();
PreparedStatement stmt = null;
String nameProd = "select * from Product where prod_name = ?";
stmt = connection.prepareStatement(nameProd);
stmt.setString(1, tf_NameProd.getText() );
ResultSet rs = stmt.executeQuery();
P.S.: I haven't compiled this code. Please put try and catch statements at appropriate places
Related
JDBC successfully connected to PostgreSQL. But some ilike query still have problems. only 1 code is working. I want the first and the third one to working properly.
--------------- not working
String ilikequery = "SELECT * FROM emp where ? iLIKE '%C%' ";
PreparedStatement ilikestatement = Main.connection.prepareStatement(ilikequery);
ilikestatement.setString(1,"name");
ResultSet resultSet = ilikestatement.executeQuery();
-------------- this one working,
String queryname = "Cowen";
String query = "select * from emp where name = ?";
PreparedStatement statement = Main.connection.prepareStatement(query);
statement.setString(1,queryname);
ResultSet resultSet = statement.executeQuery();
------------this one not working.
String ilikequerywithparameter = "SELECT * FROM emp" + " where name iLIKE '%"+"?"+"%' ";
PreparedStatement ilikestatementpara = Main.connection.prepareStatement(ilikequerywithparameter);
ilikestatementpara.setString(1,"c");
ResultSet resultSet = ilikestatementpara.executeQuery();
The last code snippet have Exception error.Exception in thread "main" org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns:
-------- this one is working.
String simpleilikequery = "SELECT * FROM emp" + " WHERE name iLIKE '%C%'";
PreparedStatement simpleilikestatement = Main.connection.prepareStatement(simpleilikequery);
ResultSet resultSet = simpleilikestatement.executeQuery();
You need to pass the wildcards as part of the parameter, not the prepared statement:
String sql = "SELECT * FROM emp where name iLIKE ?";
PreparedStatement stmt = Main.connection.prepareStatement(ilikequerywithparameter);
stmt.setString(1,"%c%");
Or alternatively use concat() in the SQL string if you don't want to (or can't) modify the parameter itself.
String sql = "SELECT * FROM emp where name iLIKE concat('%', ?, '%')";
PreparedStatement stmt = Main.connection.prepareStatement(ilikequerywithparameter);
stmt.setString(1,"c");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mystationary", "root", "");
Statement stmt = con.createStatement();
String qry;
qry = "select * from owners where usernm='" + jTextField1.getText() + "',password='" + jTextField2.getText() + "'";
ResultSet rs = stmt.executeQuery(qry);
while (rs.next()) {
JOptionPane.showMessageDialog(null, "Welcome '" + jTextField1.getText() + "' !");
}
} catch (HeadlessException | ClassNotFoundException | SQLException e) {
JOptionPane.showMessageDialog(null, e);
}
You have to use PreparedStatement instead to avoid any syntax error or SQL Injection:
try (PreparedStatement ps = con.prepareStatement(
"select * from owners where usernm = ? and password = ?")) {
ps.setString(1, jTextField1.getText());
ps.setString(2, jTextField2.getText());
ResultSet rs = ps.executeQuery(qry);
if (rs.next()) {
JOptionPane.showMessageDialog(null, "Welcome '" + jTextField1.getText() + "' !");
}
}
Your real problem is with the , when you want to use where you have to use and not ,
qry = "select * from owners where usernm='"+jTextField1.getText()+"', password='"+jTextField2.getText()+"'";
//------------------------------------------------------------------^
Instead you have to use :
qry = "select * from owners where usernm='"+jTextField1.getText()+"' and password='"+jTextField2.getText()+"'";
//-------------------------------------------------------------------^^^
But PreparedStatement is more secure.
Another thing, if you want to check for one use, then you can use if (rs.next()) instead of while (rs.next())
On this line:
qry = "select * from owners where usernm='"+jTextField1.getText()+"',password='"+jTextField2.getText()+"'";
You are using a comma to separate your conditions when you should be using the SQL operator "AND."
qry = "SELECT * FROM owners WHERE usernm='"+jTextField1.getText()+"' AND password='"+jTextField2.getText()+"'";
Also, as Dave Newton pointed out, this code is vulnerable to SQL injection. And your while loop after the executeQuery() call doesn't actually use your result set.
I am trying to use the WHERE LIKE command in my program.
My Code
String searchCriteria = searchTextField.getText();
String searchCriteria1 ="'"+"%" + searchCriteria + "%"+"'";\
String query = "select ID,Priority,recipient,Sender,Label,Subject from Messages where Message like = '" + searchCriteria1 + "'";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
Code Explained
1.What this code codes is get the input from the user.
2.Creates a string variable that contains the search condition and the "%" either side of the condition.
3.The last few lines execute the SQL query.
I am currently getting the error java.sql.SQLSyntaxErrorException: Syntax error: Encountered "=" at line 1, column 92. and not sure whats wrong with my statement.
Its most likely to be something very silly and small, I hope you can help.
Thank you
Seems as if you have single quotes twice over in the search criteria.
But you need to use prepared statement with bind parameters in this case.
You should use PreparedStatement like this:
String searchCriteria = searchTextField.getText();
String query = "select ID,Priority,recipient,Sender,Label,Subject from Messages where Message like ?";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, "%" + searchCriteria + "%");
ResultSet rs = pst.executeQuery();
Instead of putting your modulus(%) in your variable you can put it at the query itself and remove your equal(=) symbol. See below:
String searchCriteria1 =" + searchCriteria + ";
String query = "SELECT ID,Priority,recipient,Sender,Label,Subject FROM Messages WHERE Message LIKE '%" + searchCriteria1 + "%'";
How can I use the value of a combo box in a SQL query with Java?
I try this code but it doesn't work.
String sql = " select * from table1 where ? like ?";
try{
pst = conn.prepareStatement(sql);
pst.setString(1, (String) jComboBox2.getSelectedItem());
pst.setString(2, txtsearch.getText() + "%");
rs = pst.executeQuery();}
If I use this code, it works.
String sql = " select * from table1 where Name like ?";
try{
pst = conn.prepareStatement(sql);
pst.setString(1, txtsearch.getText() + "%");
rs = pst.executeQuery();}
Well, you can do something like this:
try {
String sql = "select * from table1 where ";
sql += (String) jComboBox2.getSelectedItem();
sql += " like ";
sql += txtsearch.getText() + "%";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
}
The place holder (?) is actually designed for the column values not for column/table name. Make use of string concatenation:
String sql = "select * from table1 where "
+ jComboBox2.getSelectedItem()
+" like ?";
how would i write this sql statement without a hard coded value?
resultSet = statement
.executeQuery("select * from myDatabase.myTable where name = 'john'");
// this works
rather have something like:
String name = "john";
resultSet = statement
.executeQuery("select * from myDatabase.myTable where name =" + name);
// Unknown column 'john' in 'where clause' at
// sun.reflect.NativeConstructorAccessorImpl.newInstance0...etc...
thanks in advance..
It is a terrible idea to construct SQL queries the way you currently do, as it opens the door to all sorts of SQL injection attacks. To do this properly, you'll have to use Prepared Statements instead. This will also resolve all sorts of escaping issues that you're evidently having at the moment.
PreparedStatement statement = connection.prepareStatement("select * from myDatabase.myTable where name = ?");
statement.setString(1, name);
ResultSet resultSet = statement.executeQuery();
Note that prepareStatement() is an expensive call (unless your application server uses statement caching and other similar facilities). Theoretically, it'd be best if you prepare the statement once, and then reuse it multiple times (though not concurrently):
String[] names = new String[] {"Isaac", "Hello"};
PreparedStatement statement = connection.prepareStatement("select * from myDatabase.myTable where name = ?");
for (String name: names) {
statement.setString(1, name);
ResultSet resultSet = statement.executeQuery();
...
...
statement.clearParameters();
}
You are missing the single quotes around your string, your code corrected:
String name = "john";
String sql = "select * from myDatabase.myTable where name = '" + name + "'";
// Examine the text of the query in the debugger, log it or print it out using System.out.println
resultSet = statement.executeQuery(sql);
Print out / log text of the query before executing the query to see if it looks OK.
If you are going to do a lot of similar queries where only the constant changes, consider using prepared statements
this should work:
String name = "john";
resultSet = statement
.executeQuery("select * from myDatabase.myTable where name =" + "'" + name + "'");
you need to put quotes around the value ('john' instead of john)...
Try the following :
String name = "john";
resultSet = statement
.executeQuery("select * from myDatabase.myTable where myTable.name = '" + name + "'");
Put quotes around your name value since it's a string.
"select * from myDatabase.myTable where name ='" + name + "'"