sql in java: WHERE name = variable - java

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

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

How to pass multiple parameters in sql query using Java?

I have sql query which is shown below its a select statement I want to pass dynamically the values but I am not aware how can we do it .here I want to pass product and location dynamically
can anyone help in this ..
public static ResultSet RetrieveData() throws Exception {
PreparedStatement statement;
String sql = "select * FROM Courses WHERE "
+ "product = product? "
+ "and location = location? ";
System.out.println(sql);
DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
String mysqlUrl = "jdbc:mysql://localhost:3306/wave1_build";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "root");
statement = con.prepareStatement(sql);
ResultSet rs = statement.executeQuery(sql);
return rs;
One approach is to use plain ? placeholders along with the appropriate setters to bind values:
String sql = "SELECT * FROM Courses WHERE product = ? AND location = ?";
statement = con.prepareStatement(sql);
statement.setString(1, "some product");
statement.setString(2, "some location");
// NOTE: executeQuery() when used with prepared statements does NOT take any parameters
ResultSet rs = statement.executeQuery();

Trying to join 2 tables in java but i get a Error

Im working with Sql and java.
This works in sql:
use mybank
Select * from Account
inner join CustomerAccount on accountid = id
where customerid = 18
In java i write this:
String sql = ("Select * From Account inner join CustomerAccount on accountid = id where customerid =?;");
try (Connection con = myDbManager.getConnection())
{
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, customer.getId());
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
customer.getId gives me 18.
but i get this error;
Incorrect syntax near '?'.
The problem is here:
ResultSet rs = st.executeQuery(sql);
You're using Statement#executeQuery(String sql) which is inherited from Statement interface. You should use PreparedStatement#executeQuery.
In short, change that line to:
ResultSet rs = ps.executeQuery();
^ parameter-less
And remove this Statement variable from your code, it will just confuse you and future readers of the code:
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, customer.getId());
//Statement st = con.createStatement();
^ this generates confusion
Also, you should remove the semicolon in your SQL statement when executing it form Java:
String sql = "Select *"
+ " From Account"
+ " inner join CustomerAccount"
+ " on accountid = id"
+ " where customerid = ?";
SQL-Queries in Java don't use the ';':
String sql =( "Select * From Account inner join CustomerAccount on accountid = id where customerid =?");

Use the value of a combo box in a SQL query

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

Java JDBC Query with variables?

String poster = "user";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM `prices` WHERE `poster`="+poster);
This does not work.Any tips or tricks would be appreciated.
Try surrounding the poster variable with single quotes, like this:
ResultSet rs = stmt.executeQuery("SELECT * FROM `prices` WHERE `poster`='"+poster+"'");
That's because SQL expects strings to be surrounded by single quotes. An even better alternative would be to use prepared statements:
PreparedStatement stmt = con.prepareStatement("SELECT * FROM `prices` WHERE `poster` = ?");
stmt.setString(1, poster);
ResultSet rs = stmt.executeQuery();
It's recommended using PreparedStatement since the way you are currently building the query (by concatenating strings) makes it easy for an attacker to inject arbitrary SQL code in a query, a security threat known as a SQL injection.
1) In general, to "parameterize" your query (or update), you'd use JDBC "prepared statements":
http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
2) In your case, however, I think all you need to do is add quotes (and lose the back-quotes):
// This is fine: no back-quotes needed
ResultSet rs = stmt.executeQuery("SELECT * FROM prices");
// Since the value for "poster" is a string, you need to quote it:
String poster = "user";
Statement stmt = con.createStatement();
ResultSet rs =
stmt.executeQuery("SELECT * FROM prices WHERE poster='" + poster + "'");
The Statement interface only lets you execute a simple SQL statement with no parameters. You need to use a PreparedStatement instead.
PreparedStatement pstmt = con.prepareStatement("
select * from
prices where
poster = ?");
pstmt.setString(1, poster);
ResultSet results = ps.executeQuery();

Categories