How to write sql query in an executeQuery method? - java

I have an account_holder table with a field userId and I have a data set as data.I want to select only that record from account_holder which having userId as data[3] i.e (4 field of data set). I am writing query as:
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from account_holder where userID = 'data[3]' ");
But my rs is null the entry not gets in to the ResultSet object rs. Plz tell me the correct way to write sql query with where clause inside the executeQuery() method.

As the first post said this is one way of handling this:
try {
Statement statement = connection.createStatement(); // Creating Statement
// Executing Statement
ResultSet resultSet = statement.executeQuery("SELECT * FROM account_holder WHERE userID = '" + data[3] + "'");
// Check if result set has entries
if (resultSet.first()) // If so the user already exists
System.out.println("User already exists! " + resultSet.getString("userID"));
else // If not the user does not exist
System.out.println("User does not exist!");
// Clean up
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
But in your context I would actually recommend using a PreparedStatement:
try {
// Making statement
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM account_holder WHERE userID = ?");
preparedStatement.setString(1, data[3]); // Set String for the first question mark in Query
ResultSet resultSet = preparedStatement.executeQuery(); // Executing the Prepared Statement
// Check if result set has entries
if (resultSet.first()) // If so the user already exists
System.out.println("User already exists! " + resultSet.getString("userID"));
else // If not the user does not exist
System.out.println("User does not exist!");
// Clean up
resultSet.close();
preparedStatement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}

You have to only change the query in the executeQuery method
example:
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from account_holder where userID = '"+data[3]+"' ");
or you can also run the following command:
ResultSet rs = st.executeQuery("select * from account_holder where userID = "+data[3]+"");

Related

Unable to execute prepared Statement from DAO

So currently Im trying to do get the auto-incremented primary key by following this answer
Primary key from inserted row jdbc? but apparently the program can't even reach that line and the error appeared on the ps.executeQuery() line after debugging the program, the error it display was only "executeQuery" is not a known variable in the current context. that line, which didn't make sense to me. So how do I go pass this hurdle?
public static int createNewLoginUsers(String newPassword, String newRole) throws SQLException{
Connection conn = DBConnection.getConnection();
Statement st = null;
ResultSet rs = null;
PreparedStatement ps = null;
int id = 0;
try{
String sql = "INSERT into Login(password, role) VALUES(?,?)";
ps = conn.prepareStatement(sql);
ps.setString(1, newPassword);
ps.setString(2, newRole);
ps.executeUpdate();
st = conn.createStatement();
rs = st.executeQuery("SELECT * from Login");
rs.last();
System.out.println(rs.getInt("username"));
id = rs.getInt("username");
rs.close();
} finally{
try{
conn.close();
}catch(SQLException e){
System.out.println(e);
}
}
return id;
}
The part of the method which calls the createNewLoginUsers method
if(newPasstxtfld.getText().equals(retypeNewPasstxtfld.getText())){
//update into database
try {
int username = CreateUsersDAO.createNewLoginUsers( (String) newUserRoleBox.getSelectionModel().getSelectedItem(), newPasstxtfld.getText());
Alert confirmation = new Alert(Alert.AlertType.INFORMATION);
confirmation.setHeaderText("New User Details has been created. Your username is " + username);
confirmation.showAndWait();
} catch (SQLException e) {
}
EDIT:
Databases table added and it's in the provided link below
https://imgur.com/a/Dggp2kc and edit to the codes instead of 2 try blocks in one method i have placed it into a different similar method, updated my codes to the current one I have.

Java: SQL Query: rs.next() is false after updating a column

I have a strange problem. I have a database and I want to change the values of a column. The values are safed in an Arraylist (timelist).
In order to write the values in the right row, I have a second Arrylist (namelist). So I want to read the first row in my Database, than I check the namelist and find the name. Than i take the matching value out of the timelist and write it into the database into the column "follows_date" in the row, matching to the name.
And than I read the next row of the Database, until there are no more entries.
So the strange thing is, if I change nothing in the database, the while(rs.next()) part works.
For example:
ResultSet rs = statement.executeQuery("SELECT username FROM users");
while(rs.next()){
// read the result set
String name = rs.getString("username");
System.out.println("username = " + name); //liest die namen
}
}
This would print me every name after name. But when I change the table, the while loop ends after that. (no error, the program just finishes)
ResultSet rs = statement.executeQuery("SELECT username FROM users");
while(rs.next()){
// read the result set
String name = rs.getString("username");
System.out.println("username = " + name); //writes the name
//look, if name is in Arraylist "namelist"). if yes, than write the matching date from "timelist" into the database.
if (namelist.contains(name)){
System.out.println("name found: "+ name);
int listIndizi = namelist.indexOf(name); //get index
Long indiziDatum = (long) timelist.get(listIndizi); //get date from same Index
System.out.println(indiziDatum); // print date so i can see it is correct (which it is)
statement.executeUpdate("UPDATE users SET follows_date ="+ indiziDatum +" WHERE username = '"+name+"'"); //updates the follows_date column
}
}
Everything works fine, except that now, the while loop doesn't continues after the first passage, but ends.
The resultSet of a statement is closed and will not return further results if you execute another statement. Create a new separate statement object for the update and everything should work as excepted.
Statement statement1 = connection.createStatement();
Statement statement2 = connection.createStatement();
ResultSet resultSet1 = statement1.executeQuery("SELECT username FROM users");
while(resultSet1.next()){
...
statement2.executeUpdate("UPDATE users ..."));
}
As to Why it happens:
Here is the explanation from the official documentation:
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.
Alternative Approach:
From your sample, it seems you are trying to update the "same" row in your resultSet, you should consider using an Updatable ResultSet.
Sample code from the official documentation:
public void modifyPrices(float percentage) throws SQLException {
Statement stmt = null;
try {
stmt = con.createStatement();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = stmt.executeQuery(
"SELECT * FROM " + dbName + ".COFFEES");
while (uprs.next()) {
float f = uprs.getFloat("PRICE");
uprs.updateFloat( "PRICE", f * percentage);
uprs.updateRow();
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
} finally {
if (stmt != null) { stmt.close(); }
}
}

PreparedStatement to update one value based on another in a record

I have below table structure
id msg keyword
-----------------
1 abc ?
2 xyz ?
The above is just an example; however my real table looks like that only. Based on the value of msg field, I need to call an API that would calculate the keywords from the msg and then update the particular record. How can I get the record and update as well, at the same time using Java PreparedStatement?
Also since my database is very large, what would be the efficient way to do it? Below is the code snippet :
public void updateColumns() {
try {
PreparedStatement stmt = null;
ResultSet resultSet = null;
String query = "select * from '" + Constants.tableName + "'";
// How to uypdate the record here by calling my custom API that reads the msg and returns the keywords in the message??
stmt = conn.prepareStatement(query);
stmt.execute();
stmt.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The idiomatic JDBC solution would be to generate a batch update :
String select = "SELECT id, msg FROM my_table";
String update = "UPDATE my_table SET keyword = ? WHERE id = ?";
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(select);
PreparedStatement ps = conn.prepareStatement(update);) {
while (rs.next()) {
ps.setInt(1, rs.getInt(1));
ps.setString(2, MyAPI.calculateKeyword(rs.getString(2));
ps.addBatch();
}
ps.executeBatch();
}
Of course, if you table is very large, you may which to consider every X rows.

JDBC MySql bind variable syntax error in where clause

I am getting this error:
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
public static Person getDetails(int id) {
Connection conn = null;
PreparedStatement stmt = null;
Person newPerson = new Person();
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
String sql = "SELECT firstName, lastName, birthday FROM person WHERE id=?";
System.out.println("SQL Statement:\n\t" + stmt);
stmt = conn.prepareStatement(sql);
System.out.println("Prepared Statement before bind variables set:\n\t" + stmt.toString());
//Bind values into the parameters.
System.out.println("ID " + id);
stmt.setInt(1, id); // This would set id
System.out.println("Prepared Statement after bind variables set:\n\t" + stmt.toString());
// Let us select all the records and display them.
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
Date birthday = rs.getDate("birthday");
newPerson.setBirthday(birthday);
newPerson.setFirstName(firstName);
newPerson.setLastName(lastName);
newPerson.setId(id);
//Display values
System.out.print("ID: " + id);
System.out.print(", First: " + firstName);
System.out.println(", Last: " + lastName);
System.out.println(", Birthday: " + birthday);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
return newPerson;
}
I have success executing the query without the where clause. I have looked at many examples and nothing I try fixes this.
Don't use executeQuery(String) with prepared statements...
Instead of....
ResultSet rs = stmt.executeQuery(sql);
use...
ResultSet rs = stmt.executeQuery();
Take a look at How to use Prepared Statements for more details
If I understand your question, the problem is you used Statement.executeQuery(String). I'm fairly certain you meant to use PreparedStatement.executeQuery(),
// Let us select all the records and display them.
ResultSet rs = stmt.executeQuery(sql); // <-- adding sql here makes it use the
// Statement version.
You wanted to use
// Let us select all the records and display them.
ResultSet rs = stmt.executeQuery(); // <-- use the version from PreparedStatement
Change
ResultSet rs = stmt.executeQuery(sql);
to
ResultSet rs = stmt.executeQuery();

Problems with PreparedStatement - Java

Im trying to use PreparedStatement to my SQLite searches. Statement works fine but Im getting problem with PreparedStatement.
this is my Search method:
public void searchSQL(){
try {
ps = conn.prepareStatement("select * from ?");
ps.setString(1, "clients");
rs = ps.executeQuery();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
but Im getting this error:
java.sql.SQLException: near "?": syntax error at
org.sqlite.DB.throwex(DB.java:288) at
org.sqlite.NestedDB.prepare(NestedDB.java:115) at
org.sqlite.DB.prepare(DB.java:114) at
org.sqlite.PrepStmt.(PrepStmt.java:37) at
org.sqlite.Conn.prepareStatement(Conn.java:231) at
org.sqlite.Conn.prepareStatement(Conn.java:224) at
org.sqlite.Conn.prepareStatement(Conn.java:213)
thx
Columns Parameters can be ? not the table name ;
Your method must look like this :
public void searchSQL()
{
try
{
ps = conn.prepareStatement("select * from clients");
rs = ps.executeQuery();
}
catch (SQLException ex)
{
ex.printStackTrace();
}
}
Here if I do it like this, it's working fine, see this function :
public void displayContentOfTable()
{
java.sql.ResultSet rs = null;
try
{
con = this.getConnection();
java.sql.PreparedStatement pstatement = con.prepareStatement("Select * from LoginInfo");
rs = pstatement.executeQuery();
while (rs.next())
{
String email = rs.getString(1);
String nickName = rs.getString(2);
String password = rs.getString(3);
String loginDate = rs.getString(4);
System.out.println("-----------------------------------");
System.out.println("Email : " + email);
System.out.println("NickName : " + nickName);
System.out.println("Password : " + password);
System.out.println("Login Date : " + loginDate);
System.out.println("-----------------------------------");
}
rs.close(); // Do remember to always close this, once you done
// using it's values.
}
catch(Exception e)
{
e.printStackTrace();
}
}
Make ResultSet a local variable, instead of instance variable (as done on your side). And close it once you are done with it, by writing rs.close() and rs = null.
Passing table names in a prepared statement is not possible.
The method setString is when you want to pass a variable in a where clause, for example:
select * from clients where name = ?
thx for replies guys,,,
now its working fine.
I noticed sql query cant hold ? to columns too.
So, this sql query to PreparedStatement is working:
String sql = "select * from clients where name like ?";
ps = conn.prepareStatement(sql);
ps.setString(1, "a%");
rs = ps.executeQuery();
but, if I try to use column as setString, it doesnt work:
String sql = "select * from clientes where ? like ?";
ps = conn.prepareStatement(sql);
ps.setString(1, "name");
ps.setString(2, "a%"):
rs = ps.executeQuery();
Am I correct? or how can I bypass this?
thx again

Categories