Postgresql with java: query produced no result after insert - java

I write a little program to admin my video collection.
/*
insert new data set into the table
*/
int next = 0;
rs = st.executeQuery("Select max(category_id) from category;");
if (rs.next()) {
next = rs.getInt(1) + 1;
System.out.println(next);
}
String query = "INSERT INTO category VALUES (" + next + ", 'Mystics', now());";
rs = st.executeQuery(query);
//on this place is the exception thrown
// this will not execute anymore
rs = st.executeQuery("DELETE FROM category WHERE name = 'Mystics';");
The program can select on tables, make joins but insert make trouble.
I try to insert some new data in my table (see Java-code). After the second test the output show me that the data was inserted. But after Insert was an exception thrown.
1 & 2 are the tests from yesterday and today. (3) was inserted but not selected yet.
1 Mystics 2015-07-05
2 Mystics 2015-07-06
3
org.postgresql.util.PSQLException: query produced no result.
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:287)
at postgre_java.Zetcode.main(Zetcode.java:55)
do you have some advises for me?

Do not manipulate data with read statements!
If you want to insert, update, delete data in db use
Statement stmt = conn.createStatement();
stmt.executeUpdate(SQL);
executeQuery returns resultset, but all that INSERT, UPDATE, DELETE can return is number of affected rows and that is what executeUpdate is returning.
And never, never, never*100 use string concatenation in SQL use Prepared statements!

In Java, you use executeQuery for a SELECT statement or some other statement which returns something. If you want to execute an INSERT, UPDATE or DELETE without returning something, you should use executeUpdate().

Statement#executeUpdate() is meant for that purpose
String query = "INSERT INTO category VALUES (" + next + ", 'Mystics', now());";
int noOfRows= st.executeQuery(query)
but it doesnt return a ResultSet , rather the no of rows affected that you could store into an Integer
Also your is highly vulnerable to Sql injection , try using the PreparedStatements to safeguard your code

Related

Deleting an entry in database and verify that it has been deleted - still finding the entry after deleting it

I have a JDCB program that connects to a MySQL database, and doing things like adding tables, adding entries, removing entries etc.
I have a problem in a test where i wanna do these steps:
Add a entry to my database table.
Check that the entry exists.
Remove the entry.
Verify that the entry no longer exists.
Here is my code:
testConn = database.getConn();
try {
String addEntry = "INSERT INTO HighScore(ID, username, " +
"Score) VALUES" +
"(ID, 'testAddEntry',333)";
st = testConn.createStatement();
st.execute(addEntry);
String findEntry = "SELECT * FROM HighScore WHERE " +
"username='testAddEntry'";
st.execute(findEntry);
assertTrue(st.execute(findEntry));
String deleteEntry = "DELETE FROM HighScore WHERE " +
"username='testAddEntry'";
st.execute(deleteEntry);
String findEntryNow = "SELECT * FROM HighScore WHERE " +
"username='testAddEntry'";
System.out.println(st.execute(findEntryNow));
assertFalse(st.execute(findEntryNow));
} catch (SQLException e) {
e.printStackTrace();
}
And the problem is that assertFalse(st.execute(findEntryNow)); should return false, but it returns true. And when I check the database the entry is not there. ( i have tried to only add and remove it, so that 100% works).
The problem is i want to run a execute that looks for it but verifies that the entry is not there.
You don't say which version of MySQL you are using, but from the docs MySQL Connector/J 5.1
If you do not know ahead of time whether the SQL statement will be a
SELECT or an UPDATE/INSERT, then you can use the execute(String SQL)
method. This method will return true if the SQL query was a SELECT, or
false if it was an UPDATE, INSERT, or DELETE statement. If the
statement was a SELECT query, you can retrieve the results by calling
the getResultSet() method. If the statement was an UPDATE, INSERT, or
DELETE statement, you can retrieve the affected rows count by calling
getUpdateCount() on the Statement instance.
This states that if you use execute to run a SELECT you will always get true.
From this page https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-usagenotes-statements.html
You will actually need to get the result set and confirm it is empty.
You are misinterpreting the meaning of the return value of Statement.execute:
Returns:
true if the first result is a ResultSet object; false if it is an update count or there are no results
A select query always has a result, and that result is a ResultSet, even if it is empty. The "there are no results" in this documentation refers to statements that produce no results at all (no update counts nor result sets).
So the return value of execute(String) does not indicate the presence or absence of rows. If you want to check that, you need to check ResultSet.next(), or - alternatively - query the count and check that that count is 0.
Option 1:
String findEntryNow = "SELECT * FROM HighScore WHERE " +
"username='testAddEntry'";
try (ResultSet rs = st.executeQuery(findEntryNow)) {
assertFalse(rs.next());
}
Option 2
String findEntryCount = "SELECT count(*) FROM HighScore WHERE " +
"username='testAddEntry'";
try (ResultSet rs = st.executeQuery(findEntryNow)) {
assertTrue(rs.next()); // even absence of entries will produce a row
assertEquals(0, rs.getInt(1));
}

My query is giving following error,Unexpected token WHERE

i'm working in java with sql.when ever this query is executed it gives me the error mentioned in title
try(PreparedStatement statement = conn.prepareStatement("INSERT INTO student_signup(q" + strId + ")" + "WHERE student_email="+email+"VALUES(?)")) {
statement.setString(1, SelectedOption);
statement.executeUpdate();
statement.close();
for a little code background
here
int questionID=1;
String strId = Integer.toString(questionID);
String email = signInForm.getTxtEmail().getText();
INSERT inserts new rows. I think you want to change a value in an existing row. For that, use UPDATE. Something like this:
UPDATE student_signup
SET strID = ?
WHERE student_email = ?;
INSERT is never use with WHERE clause
If you want to change the value for a pre-existing record in the database, you should try the UPDATE clause with WHERE condition after it.

SQL statement returns a resultset on an empty table

String sql = "Select MAX(ORDERLINEID) From ORDERLINESTABLE";
ResultSet rst;
rst = stmt.executeQuery(sql);
if(rst.next())
{
next = rst.getInt("ORDERLINEID");
next++;
}
I have a table called ORDERLINESTABLE in my database which is currently empty. I have run the above code with the aim is to get the highest integer stored in the ORDERLINEID column allowing me to increment it when adding items to the database.
I expected this query to return nothing as the table is empty but when debugging I noticed that the search is returning true for the rst.next() method.
Does anyone have any idea why this would be? I have looked at the resultset.next() documentation and as far as I can see it should return false.
When in doubt, look at your data. Here is a sample query from any db engine.
select max(field) maxValue
from table
where 1=3
It will yield
maxValue
Null
In other words, your query is returning one record with a value of null.
It is much better to fetch the ORDERLINEID filled in by the database after the INSERT statement. Make the column ORDERLINEID of type INT AUTOINCREMENT.
String sql = "INSERT INTO ORDERLINESTABLE(xxx, yyy) VALUES (?, ?)";
try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
stmt.setString(1, xxx);
stmt.setInt(2, yyy);
int updateCount = stmt.executeUpdate(); // 1
try (ResultSet id = stmt.getGeneratedKeys()) {
if (id.next()) { // 'if' as just 1 row inserted.
int orderLineId = id.getInt(1); // 1 key per row.
}
}
}
Java has a database independent way to fetch the generated keys of an INSERT. That is a lot safer than taking the MAX afterwards or before, in a multi-user environment.
Scenarios for wrong IDs are numerous in a multiuser environment:
first SELECT
second SELECT
second increment for new ID
first increment for new ID
first INSERT
second INSERT

How to get all the rows affected by a UPDATE query in JDBC?

I have an assignment where I need to update records using a PreparedStatement. Once the record have been updated as we know update query return count, i.e., number of row affected.
However, instead of the count I want the rows that were affected by update query in response, or at least a list of id values for the rows that were affected.
This my update query.
UPDATE User_Information uInfo SET address = uInfo.contact_number || uInfo.address where uInfo.user_id between ? AND ?;
Normally it will return count of row affected but in my case query should return the ids of row or all the row affected.
I have used the returning function of PostgreSQL it is working but is not useful for me in that case.
i have used returning function of PostgreSQL but is not useful for me
It should be. Perhaps you were just using it wrong. This code works for me:
sql = "UPDATE table1 SET customer = customer || 'X' WHERE customer LIKE 'ba%' RETURNING id";
try (PreparedStatement s = conn.prepareStatement(sql)) {
s.execute(); // perform the UPDATE
try (ResultSet rs = s.getResultSet()) {
// loop through rows from the RETURNING clause
while (rs.next()) {
System.out.println(rs.getInt("id")); // print the "id" value of the updated row
}
}
}
The documentation indicates that we can also use RETURNING * if we want the ResultSet to include the entire updated row.
Update:
As #CraigRinger suggests in his comment, the PostgreSQL JDBC driver does actually support .getGeneratedKeys() for UPDATE statements too, so this code worked for me as well:
sql = "UPDATE table1 SET customer = customer || 'X' WHERE customer LIKE 'ba%'";
try (PreparedStatement s = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
s.execute(); // perform the UPDATE
try (ResultSet rs = s.getGeneratedKeys()) {
while (rs.next()) {
System.out.println(rs.getInt(1)); // print the "id" value of the updated row
}
}
}
Thanks, Craig!
You might be able to use JDBC's support for getting generated keys. See the Connection.prepareStatement(String sql, int[] columnIndexes) API method, then use Statement.getGeneratedKeys() to access the results.
The spec says "the driver will ignore the array if the SQL statement is not an INSERT statement" but I think PostgreSQL's JDBC driver will actually honour your request with other statement types too.
e.g.
PreparedStatement s = conn.prepareStatement(sql, new String[] {'id'})
s.executeUpdate();
ResultSet rs = s.getGeneratedKeys();
Otherwise, use RETURNING, as Gord Thompson describes.
There are two way of doing it
1. by passing an array of column name or index of column prepareStatement
i.e conn.prepareStatement(sql, new String[] {'id','uname'})
and
2. by using Statement.RETURN_GENERATED_KEYS in prepareStatement.
My code is for this i.e as per my requirement i have developed my code you can have a look for better idea.
private static final String UPDATE_USER_QUERY= "UPDATE User_Information uInfo SET address = uInfo.contact_number || uInfo.address where uInfo.user_id between ? AND ?;";
//pst = connection.prepareStatement(UPDATE_USER_QUERY,columnNames);
pst = connection.prepareStatement(UPDATE_USER_QUERY,Statement.RETURN_GENERATED_KEYS);
ResultSet rst = pst.getGeneratedKeys();
List<UserInformation> userInformationList = new ArrayList<UserInformation>();
UserInformation userInformation;
while (rst.next()){
userInformation = new UserInformation();
userInformation.setUserId(rst.getLong("user_id"));
userInformation.setUserName(rst.getString("user_name"));
userInformation.setUserLName(rst.getString("user_lName"));
userInformation.setAddress(rst.getString("address"));
userInformation.setContactNumber(rst.getLong("contact_number"));
userInformationList.add(userInformation);
}
That think i need to achieve in this case.
Hope so this will help you a lot.

Execute multiple SQL statements (CRUD) with JDBC

I am using Java (JDBC) to create a command line utility for SQL statement execution. A script is defined as a text file, having many queries. Each query is separated by a query separator (";"). The output is routed to stdout.
SELECT * FROM table1;
UPDATE table1 SET field1='' WHERE field2='';
SELECT * FROM table1;
INSERT INTO table1 VALUES(...)
SELECT * FROM table1;
Since JDBC can execute statements batchwise, only if they don't return a ResultSet, I need another approach.
As of now, I would read the script file with the queries, split them by the separator, and analyze each query, whether it's a "SELECT" query, or an "INSERT", "UPDATE", "DELETE" query. After that, I would execute each query in it's own statement. The ones that return something are written to stdout, the queries that manipulate the database are executed. And, of course I would keep the order of the queries from the file.
My problem is: If one of the queries in the file is wrong, I can't rollback, because each query is executed separately. How could I handle this issue?
For your database connection, just call connection.setAutoCommit(false) then execute your statements and call connection.commit() when you're finished, or connection.rollback() if you encounter an error.
This is the code for for adding queries to batch.
Statement stmt = conn.createStatement();
conn.setAutoCommit(false);
String SQL = "INSERT INTO table1 VALUES(...)";
stmt.addBatch(SQL);
String SQL = "INSERT INTO Employees (id, first, last, age) " +
"VALUES(201,'Raj', 'Kumar', 35)";
stmt.addBatch(SQL);
String SQL = "UPDATE Employees SET age = 35 " +
"WHERE id = 100";
stmt.addBatch(SQL);
int[] count = stmt.executeBatch();
//Explicitly commit statements to apply changes
conn.commit();
Try this.....
This code might helpful to you.
String Query1 = "SELECT * FROM Tablename1";
stmt1 = con.createStatement();
ResultSet rs = stmt1.executeQuery(Query1);
rs.next();
int totalQuery1Count = rs.getInt("TOTAL_Item");
String Query2 = "SELECT * FROM Tablename2";
rs = stmt1.executeQuery(Query2);
rs.next();
int totalQuery2Count = rs.getInt("TOTAL_Item2");

Categories