Select * From java with preparedStatement [duplicate] - java

This question already has answers here:
Java MYSQL Prepared Statement Error: Check syntax to use near '?' at line 1
(2 answers)
Closed 1 year ago.
I faced this problem today with my select SQL. This method is supposed to show data from database in tex tfields. I changed it from statement to preparedStatement, but I faced a problem.
public Entreprise loadDataModify(String id) {
Entreprise e = new Entreprise();
PreparedStatement stmt;
try {
String sql = "SELECT * FROM user WHERE mail=?";
stmt = cnx.prepareStatement(sql);
stmt.setString(1, id);
ResultSet rst = stmt.executeQuery(sql);
while (rst.next()) {
stmt.setString(2, e.getNom());
stmt.setString(3, e.getEmail());
stmt.setString(4, e.getTel());
stmt.setString(5, e.getOffre());
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
return e;
}
It shows i have problem with syntax and the output is " nu

You're calling the wrong method. Unlike Statement, when you're using a PreperedStatement you should first set the values for the parameters, and after you can call on that instance executeQuery() method.
Also, it's a best practice to use try-with-resources, because a Statement or PreparedStament object is a Resource (a resource is a class that implements AutoCloseable interface) and you have to close it. Using try-with-resources, it's done automatically.
The ResultSet instance is also a resource, but it's closed when the statement object is closed, so you don't have to close it explicitly.
So, the best way to solve your problem will be:
String selectAllByMail = "SELECT * FROM user WHERE mail=?";
try (PreparedStatement prpStatement = connection.prepareStatement(selectAllByMail)) {
// use prpStatement
prpStatement.setString(1, id);
ResultSet resultSet = prpStatement.executeQuery();
while (resultSet.next()) {
// process resultSet
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}

You are not filling your Enterprise object. And you are not using executeQuery() function correctly. As seen below, the parameter inside the brackets has been removed. PreparedStatements first of all need the values of the parameters (your ? in the query) and then the formed query has to be executed. If you give a String parameter to executeQuery() then the query in the brackets will be executed.
And the part where Enterprise is being filled could be seen below.
This would be the correct way:
public Entreprise loadDataModify(String id) {
Entreprise e = new Entreprise();
PreparedStatement stmt;
try {
String sql = "SELECT * FROM user WHERE mail=?";
stmt = cnx.prepareStatement(sql);
stmt.setString(1, id);
ResultSet rst = stmt.executeQuery();
while (rst.next())
{
// rst keeps the data, so you have to traverse it and get the data from it in this way.
e.setNom( rst.getString("HERE EITHER THE COLUMN NAME OR INDEX"));
e.setEmail( rst.getString("HERE EITHER THE COLUMN NAME OR INDEX"));
e.setTel( rst.getString("HERE EITHER THE COLUMN NAME OR INDEX"));
e.setOffre( rst.getString("HERE EITHER THE COLUMN NAME OR INDEX"));
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
return e;
}

Your call to executeQuery() should not be passing the query string. Use this version:
String sql = "SELECT * FROM user WHERE mail=?";
stmt = cnx.prepareStatement(sql);
stmt.setString(1, id);
ResultSet rst = stmt.executeQuery();
while (rst.next()) {
// process result set
}
Your current code is actually calling some overloaded Statement#executeQuery() method, which is not the version of the method which you want to be calling.

Related

SQL Lite Query (between in dates) doesn't work

in my small test program I have some SQL Queries. The first SELECT * FROM kilometer; works properly and returns all the columns in the table. So in Java embedded, ResultSet rs = stmt.executeQuery("SELECT * FROM kilometer;"); returns an ResultSet which is not empty.
Now I wanted to get only the rows within a specific date. But my embedded query ResultSet rs = stmt.executeQuery("SELECT * FROM kilometer WHERE datum BETWEEN '2016-01-01' AND '2016-12-31';"); returns an empty ResultSet. But I've tested it online and it worked properly. Where is my mistake? I've consulted already some pages like this, but I can't find the mistake.
I am using SQLite 3.15.1 and Java SE 8.
Full java code:
public ArrayList<Strecke> getErgebnisse(final String startzeitpunkt, final String zielzeitpunkt) {
ArrayList<Strecke> strecken = new ArrayList<>();
try {
try {
if (connection != null) {
}
connection = DriverManager.getConnection("jdbc:sqlite:" + DB_PATH);
if (!connection.isClosed())
} catch (SQLException e) {
throw new RuntimeException(e);
}
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM kilometer WHERE datum BETWEEN '2016-01-01' AND '2016-12-31';");
while (rs.next()) {
strecken.add(new Strecke(Instant.ofEpochMilli(rs.getDate("datum").getTime()).atZone(ZoneId.systemDefault()).toLocalDate(), rs.getString("startort"), rs.getString("zielort"), rs.getDouble("kilometer")));
}
rs.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
return strecken;
}
First of all I would recommend that you use prepared statements while executing your queries instead of passing the query directly as a string......secondly I believe the problem here is that you are passing the date as a string in quotes and not a date.....I think that is the issue here. You would need to use sqllites datetime functions for this....

Getting wrong output in PreparedStatement [duplicate]

This question already has answers here:
mysql prepared statement error: MySQLSyntaxErrorException
(2 answers)
Closed 6 years ago.
I've a course table with the columns,
id, teacher_id and name.
This is the method that I'm using to get a course by id.
public static Course getById(int id) throws SQLException {
String query = "SELECT * FROM courses WHERE id = ?" ;
Course course = new Course();
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try{
DriverManager.registerDriver(new com.mysql.jdbc.Driver ());
connection = (Connection) DriverManager.getConnection(ConnectDb.CONN_STRING, ConnectDb.USERNAME, ConnectDb.PASSWORD);
statement = (PreparedStatement) connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
statement.setInt(1, id);
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
course.setId(resultSet.getInt("id"));
course.setName(resultSet.getString("name"));
course.setTeacherId(resultSet.getInt("teacher_id"));
}
}catch (SQLException e) {
System.err.println(e);
}finally{
if (resultSet != null) resultSet.close();;
if (statement != null) statement.close();
if(connection != null) connection.close();
}
return course;
}// end of method
When I run this method, I get an output id :0, teacher_id : 0
The server log says that I've an SQLException
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1
The bug is here:
resultSet = statement.executeQuery(query);
You're not calling PreparedStatement#executeQuery, you're calling Statement#executeQuery (Statement is a superinterface of PreparedStatement). So the parameter substitution isn't happening and you're actually sending that ? to the server.
Change it to:
resultSet = statement.executeQuery();
// No argument here ---------------^
(And yes, this is an API design flaw; and no, you're not the first to fall into it.)
There are a few other things about that code that could use improvement:
You're always returning a Course, even if an exception occurred. Best practices would be to allow the exception to propagate to the caller; second-best practices would be to return some kind of flag to the caller that an error occurred, such as null.
The try-with-resources statement can make that code both shorter and clearer
You shouldn't have to cast the return values of getConnection or prepareStatement.
You're using while, but you're expecting only a single result. if would make more sense.
On that topic, you can give the driver a hint in that regard by using setMaxRows.
Your method declares that it can throw SQLException, which is literally true since it calls close, but the only useful SQLException is actually being caught, logged, and suppressed by the code, making declaring it on the method a bit misleading.
I'm told modern JDBC drivers don't need the registerDriver call anymore. (I personally haven't used JDBC for a while now, so...)
Here's an example incoporating the above. It allows an exception to propagate, so errors (exceptional conditions) are not handled in the normal flow of code; it returns null if there's no matching course:
public static Course getById(int id) throws SQLException {
String query = "SELECT * FROM courses WHERE id = ?";
try (
Connection connection = DriverManager.getConnection(ConnectDb.CONN_STRING, ConnectDb.USERNAME, ConnectDb.PASSWORD);
PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
) {
statement.setInt(1, id);
statement.setMaxRows(1);
try (
ResultSet resultSet = statement.executeQuery();
) {
if (resultSet.next()) {
Course course = new Course();
course.setId(resultSet.getInt("id"));
course.setName(resultSet.getString("name"));
course.setTeacherId(resultSet.getInt("teacher_id"));
return course;
}
// No matching course
return null;
}
}
} // end of method
That can probably be improved further, but you get the idea.

Mysql select prepared statement in JAVA [duplicate]

This question already has answers here:
Using Prepared Statements to set Table Name
(8 answers)
Closed 6 years ago.
this is my current java program. I need to make a prepared statement and connect to a MySql database.
try {
Connection connect = DriverManager.getConnection(host, username, password);
System.out.println("works fine connected");
/*
*
* */
String Dquery = ("SELECT * FROM ?");
//create the java statement
PreparedStatement st = connect.prepareStatement(Dquery);
st.setString(1, "lmgs_Book");
System.out.println("mySql statemnt: "+Dquery);
//execute the query, and get a java resultset
ResultSet rs = st.executeQuery();
//iterate through the java resultset
while (rs.next())
{
String id = rs.getString(Column1);
String firstName = rs.getString(Column2);/*
String lastName = rs.getString(Column3);
String dateCreated = rs.getString(Column4);
int isAdmin = rs.getInt (Column5);*/
//print the results
System.out.println(id+"|\t"+firstName/*+"|\t\t"+lastName+"|\t\t"+dateCreated+"|\t"+isAdmin*/);
}
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I cant insert the "lmgs_Book" String into the prepared statement.
Prepared statement is for the column values not for table name.
But you can use placeholder in place of table name and then replacing
that with your tablename.
String Dquery = ("SELECT * FROM $tableName");
Dquery = Dquery.replace("$tableName","lmgs_Book");
PreparedStatement st = connect.prepareStatement(Dquery);
Remove this:
st.setString(1, "lmgs_Book");
Caution:
And what is the advantage compared to
String Dquery = "SELECT * FROM lmgs_Book";? [Recommended]
Answer: No advantage at all. You may embrace potential harms if you use placeholder in table name like above.
(especially since you should not use a variable in the replace call
instead of the literal, since that might make the statement vulnerable
to SQL injection)
try this and Please make sure your queryString column Name must be a varchar in your database.
String Dquery = ("SELECT * FROM tablename where column_name =?");
//create the java statement
PreparedStatement st = connect.prepareStatement(Dquery);
st.setString(1, "lmgs_Book"); //this line will be set Imgs Books as search Parameter.

Get the results after the it is closed

I am using the sqlite driver with java. As you know the typical order is
Create Statement
Execute Statement
Get ResultSet
Process Results
close ResultSet
close statement
The problem is that all of above is in one method and I want the caller to get the results and process it. However since the results are returned at the end of the method then by then the statement and the result set is closed.
The only work around I can think of is to have the RS and the Stmnt be a class variable and have the caller close them but this will pose problem if it is multi threaded env.
What is the recommended way to achieve what I want?
Thanks
public ResultSet runQuery(String sql) {
try {
st = conn.createStatement();
rs = st.executeQuery(sql);
rs.close();
st.close()
} catch (SQLException ex) {
Logger.getLogger(DatabaseHelper.class.getName()).log(Level.SEVERE, null, ex);
}
return rs
}
From another file
private void displayListOfEmployee(){
String sql = "Select * from employee";
ResultSet rs = DB.getInstance().runQuery(sql);
while(rs.next()!=null){
System.out.println(.....); // display value of column
}
}
You can add a Consumer<ResultSet> parameter to the method:
public void query(String query, Consumer<ResultSet> consumer) {
// Create Statement
try (Statement stmt = ...) {
// Execute Statement
ResultSet rs = ...
consumer.accept(rs);
}
}
With this the caller can extract its data from the result set and you can guarantee that resources are closed.
A variation would be to use a Function parameter and compute a return value:
public <T> T query(String query, Function<ResultSet,T> function) {
// Create Statement
try (Statement stmt = ...) {
// Execute Statement
ResultSet rs = ...
return function.apply(rs);
}
}
Since Consumer.accept and Function.apply do not allow to throw checked exceptions you may want to define similar functional interfaces which allow checked exceptions and use it in that method.
UPDATE:
Your example would translate to:
private void displayListOfEmployee(){
String sql = "Select * from employee";
DB.getInstance().runQuery(sql, rs -> {
while (rs.next())
System.out.println(.....); // display value of column
});
}
A possible solution would be to use a CachedRowSet, which is populated from a ResultSet but can outlive the associated Statement/Connection the ResultSet was produced by.
Note this will read the entire ResultSet into memory.

Getting java.sql.SQLException: Operation not allowed after ResultSet closed

When I execute the following code, I get an exception. I think it is because I'm preparing in new statement with he same connection object. How should I rewrite this so that I can create a prepared statement AND get to use rs2? Do I have to create a new connection object even if the connection is to the same DB?
try
{
//Get some stuff
String name = "";
String sql = "SELECT `name` FROM `user` WHERE `id` = " + userId + " LIMIT 1;";
ResultSet rs = statement.executeQuery(sql);
if(rs.next())
{
name = rs.getString("name");
}
String sql2 = "SELECT `id` FROM `profiles` WHERE `id` =" + profId + ";";
ResultSet rs2 = statement.executeQuery(sql2);
String updateSql = "INSERT INTO `blah`............";
PreparedStatement pst = (PreparedStatement)connection.prepareStatement(updateSql);
while(rs2.next())
{
int id = rs2.getInt("id");
int stuff = getStuff(id);
pst.setInt(1, stuff);
pst.addBatch();
}
pst.executeBatch();
}
catch (Exception e)
{
e.printStackTrace();
}
private int getStuff(int id)
{
try
{
String sql = "SELECT ......;";
ResultSet rs = statement.executeQuery(sql);
if(rs.next())
{
return rs.getInt("something");
}
return -1;
}//code continues
The problem is with the way you fetch data in getStuff(). Each time you visit getStuff() you obtain a fresh ResultSet but you don't close it.
This violates the expectation of the Statement class (see here - http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html):
By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.
What makes things even worse is the rs from the calling code. It is also derived off-of the statement field but it is not closed.
Bottom line: you have several ResultSet pertaining to the same Statement object concurrently opened.
A ResultSet object is automatically
closed when the Statement object that
generated it is closed, re-executed,
or used to retrieve the next result
from a sequence of multiple results.
I guess after while(rs2.next()) you are trying to access something from rs1. But it's already closed since you reexecuted statement to get rs2 from it. Since you didn't close it, I beleive it's used again below.

Categories