Use the value of a combo box in a SQL query - java

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 ?";

Related

JDBC ilike query java

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");

I have written this code for fetch record from my table name is owners... but some error is occurs... is there something missing?

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.

How to do INSERT SELECT INTO in Java using PrepareStatement

I'm trying to do an INSERT INTO SELECT which are inserting into in 1 table by selecting specific data in columns from 2 tables. The thing is, it will involve with user input from JTextField as well. I have searched for many solutions but still got an error and I just dunno what else to do. I'm using Java as PL and Oracle as DB. This is what I have got so far :
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","ghost","slayer");
stmt = con.createStatement();
String sbjC = sbjCode.getText(); //textfield for subjectCode
String sbjN = sbjName.getText(); //textfield for subjectName
String matricsno = textstudentid.getText(); //textfield for matrics number
String sbjG = sbjGrade.getText(); //textfield for subjectGrade (not gonna be use in db, just for comparison)
String sql1 = "INSERT INTO transferred (subjectCode,subjectName,credit,prequisite,matricsNo) "
+ "SELECT b.subjectCode,b.subjectName,b.credit,b.prequisite,s.matricsNo "
+ "FROM bitm b, student s "
+ "WHERE b.subjectCode = '"+sbjC+"' AND b.subjectName = '"+sbjN+"' AND s.matricsNo = '"+matricsno+"'";
/* table Transferred has 5 column which are subjectCode,subjectName,credit,prequisite,matricsNo [matricsno as FK]
* table bitm has 5 column [subjectCode as PK]
* table student has 6 column [matricsno as PK]
*/
ps = con.prepareStatement(sql1);
ps.setString(1, sbjC);
ps.setString(2, sbjN);
ps.setString(3, "SELECT credit FROM bitm WHERE subjectCode = '"+sbjC+"' AND subjectName = '"+sbjN+"'");
ps.setString(4, "SELECT prequisite FROM bitm WHERE subjectCode = '"+sbjC+"' AND subjectName = '"+sbjN+"'");
ps.setString(5, "SELECT matricsno FROM student WHERE matricsno = '"+matricsno+"'");
ps.executeUpdate(sql1);
The only error I have got after executing and insert all data needed into JTextField is java.sql.SQLException : Invalid column index.
The SQL statement has been test in SQL Developer and succeed. Just I'm bit confused on how to do it on Java.
Thank you for all of your response and time.
I'm a newbie in Java.
For PreparedStatement, you'd code ? Into the sql and later replace that with values.
String sql1 = "INSERT INTO transferred (subjectCode,subjectName,credit,prequisite,matricsNo) "
+ "SELECT b.subjectCode,b.subjectName,b.credit,b.prequisite,s.matricsNo "
+ "FROM bitm b, student s "
+ "WHERE b.subjectCode = ? AND b.subjectName = ? AND s.matricsNo = ? ";
ps = con.prepareStatement(sql1);
ps.setString(1, sbjC);
ps.setString(2, sbjN);
ps.setString(3,matricsno);
ps.executeUpdate ();
This should do it.
Your error came from giving parameters (setString...) without matching ?
Unfortunately you absolutely misunderstood what the preparedStatemet does.
You have to write ? -s into the query and the preparedSatement is going to replace it on a typed way:
String sql1 = "INSERT INTO transferred (subjectCode,subjectName,credit,prequisite,matricsNo) "
+ "SELECT b.subjectCode,b.subjectName,b.credit,b.prequisite,s.matricsNo "
+ "FROM bitm b, student s "
+ "WHERE b.subjectCode = ? AND b.subjectName = ? AND s.matricsNo = ?";
ps = con.prepareStatement(sql1);
ps.setString(1, sbjC);
ps.setString(2, sbjN);
ps.setString(3, matNo);
ps.executeUpdate();
To answer my own question, I'll put comment on the changes that I have made to the code and make it work:
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","aza","jaiza");
stmt = con.createStatement();
String sbjC = sbjCode.getText();
String sbjN = sbjName.getText();
String matricsno = textstudentid.getText();
String sbjG = sbjGrade.getText();
String sql1 = "INSERT INTO transferred (subjectCode,subjectName,credit,prequisite,matricsNo) "
+ "SELECT b.subjectCode,b.subjectName,b.credit,b.prequisite,s.matricsNo "
+ "FROM bitm b, student s "
+ "WHERE b.subjectCode = ? AND b.subjectName = ? AND s.matricsNo = ?"; // from textfield to ?
ps = con.prepareStatement(sql1);
ps.setString(1, sbjC);
ps.setString(2, sbjN);
ps.setString(3, matricsno);
//from all the SELECT statement to just 3 user-input-from-textfield column
ps.executeUpdate(); // remove the sql1 in ps.executeUpdate(sql1);

What's wrong with this SQL command?

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

sql in java: WHERE name = variable

This is my code:
public static List GetList(String myname) {
.
.
ResultSet result = stmt.executeQuery("SELECT * FROM authors WHERE name = ?");
result.setString(myname);
}
I want to select where name = myname (myname is the input of the function).
I tried also something like:
WHERE name = #myname
but it doesn't work :/
You don't set the value on the result but on the statement:
PreparedStatement pstmt = connection.prepareStatement("SELECT * FROM authors WHERE name = ?");
pstmt.setString(1, myname);
ResultSet result = pstmt.executeQuery();
Well, a better way to go is to use PreparedStatement, to avoid SQL Injection: -
PreparedStatement stmt = con.prepareStatement("SELECT * FROM authors WHERE name = ?");
stmt.setString(1, myname);
ResultSet res = stmt.executeQuery();
However, just to solve your issue, you can use String Concatenation: -
stmt.executeQuery("SELECT * FROM authors WHERE name = '" + myname + "'");
If I'm not mistaken, you'd be better off with prepared statements here:
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM authors WHERE name = ?");
stmt.setString(1, myname);
ResultSet result = stmt.executeQuery();
try this:
ResultSet result = stmt.executeQuery("SELECT * FROM authors WHERE name = " + myname);

Categories