SQLException deleting row from JTable and database - java

I want to delete selcetd row in a JTable from both the table itself and the database.
That is my code:
Object number = jTable1.getValueAt(selectedRow-1, 0);
String sql = "delete from orders where number ="+number;
Statement st = conn.createStatement();
rs = null;
rs = st.executeQuery(sql);
When the excuteQuery() runs I get the following exception:
(java.sql.SQLException) java.sql.SQLException: Can not issue data manipulation statements with executeQuery()
What am I doing wrong?

It is not an Abnormal Exception.
You need to call executeUpdate instead of executeQuery. You cannot update database by calling executeQuery method. To update something in database (insert, update, delete) you need to call executeUpdate method and it will not return the ResultSet and instead return you an int value.
int result = st.executeUpdate(sql);
More Info

Related

Why is the resultSet.getInt (1); necessary in the following code?

As far as I know getInt(column index)retrieves a column value from the current row, but I don't understand its purpose in a situation like this. Doesn't the SQL statement SELECT COUNT(*) FROM Gyujtoallomasok
already count the rows in the table? If so, why do we need the rest?
public int count() {
try (Connection connection = DriverManager.getConnection(URL);
Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery("SELECT COUNT(*) FROM Gyujtoallomasok");
if (resultSet.next()) {
int count = resultSet.getInt(1);
return count;
}
} catch (SQLException exception) {
// TODO: log
}
return -1;
}
The method executeQuery() returns a ResultSet object and not an integer value.
The statement:
SELECT COUNT(*) FROM Gyujtoallomasok
counts the rows in the table and returns this result in the unnamed column COUNT(*).
To get this result you must extract it from the ResultSet object with the method getInt(), since the result is an integer, by passing the index 1 of the column (it is the 1st and only column in the ResultSet):
resultSet.getInt(1)
If you aliased the column like this:
SELECT COUNT(*) AS counter FROM Gyujtoallomasok
you could also get its value with:
resultSet.getInt("counter")
getInt is still needed since this line:
ResultSet resultSet = statement.executeQuery("SELECT COUNT(*) FROM Gyujtoallomasok");
is placing what is returned from the database into a ResultSet which is "A table of data representing a database result set".
You then must iterate through the ResultSet to retrieve your answer which is what resultSet.next() and resultSet.getInt(); are doing.

Resultset is slow for oracle ref cursor

Getting a cursor result set from procedure and iterating it is much slower than query result set. I have a procedure which returns a cursor but it took 5s to fetch the next result set.
String callProcedure = "{ call SCHEMANAME.TEMP_PACKAGE.GET_CURSOR_RESULTS(?,?,?,?) }";
cs = con.prepareCall(callProcedure);
cs.setString(1, "Variable1");
cs.setString(2,"Variable2");
cs.setString(3,"Variable3");
cs.registerOutParameter(4, OracleTypes.CURSOR);
ResultSet rs = (ResultSet) cs.getObject(4);
while (rs.next()){
}
I have used logs and found that rs.next() get 5-6 seconds.
So I have changed the logic as below,
String callProcedure = "{ call SCHEMANAME.TEMP_PACKAGE.GET_CURSOR_RESULTS(?,?,?,?,?) }";
cs = con.prepareCall(callProcedure);
cs.setString(1, "Variable1");
cs.setString(2,"Variable2");
cs.setString(3,"Variable3");
cs.registerOutParameter(4,java.sql.Types.VARCHAR);
cs.registerOutParameter(5,java.sql.Types.INTEGER);
I got those parameters from the procedure and use a preparedStatement to execute the query which was used in the cursor.
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next()){
}
Above approach is faster than using a sys_refcursor. Please explain why using sys_refcursor taking much time than a normal query.
PS: Cursor will not return more than 20 rows.
Thanks.
this should be helpful
http://docs.oracle.com/cd/E11882_01/java.112/e16548/resltset.htm#JJDBC28621
By default, when Oracle JDBC runs a query, it retrieves a result set
of 10 rows at a time from the database cursor. This is the default
Oracle row fetch size value. You can change the number of rows
retrieved with each trip to the database cursor by changing the row
fetch size value.
Statement, PreparedStatement, CallableStatement, and ResultSet objects for setting and getting the fetch size:
void setFetchSize(int rows) throws SQLException
int getFetchSize() throws SQLException

Get specific row in ResultSet?

After getting results from a SQL query, I can access the results via a while loop :
String query = "SELECT TAX_RATE_ID FROM dbo.TAX_RATE where zip_code = 38401";
ResultSet rs= conn.createStatement().executeQuery(query);
while (rs.next()) {
System.out.println(rs.getString("TAX_RATE_ID"));
}
But I don't want to access them in a while loop, I want to just get the single result and return the value, since I know what to expect when the query is ran. So I tried this:
String query = "SELECT TAX_RATE_ID FROM dbo.TAX_RATE where zip_code = 38401";
ResultSet rs= conn.createStatement().executeQuery(query);
rs.first();
System.out.println(rs.getString("TAX_RATE_ID"));
But I get this error:
Exception in thread "main" java.sql.SQLException: ResultSet may only be accessed in a forward direction.
at net.sourceforge.jtds.jdbc.JtdsResultSet.checkScrollable(JtdsResultSet.java:319)
at net.sourceforge.jtds.jdbc.JtdsResultSet.first(JtdsResultSet.java:545)
at com.kirklands.automation.ecom.Testing.main(Testing.java:12)
You don't have to call next() in a loop. If you just want to get the first row, use:
String query = "SELECT TAX_RATE_ID FROM dbo.TAX_RATE where zip_code = 38401";
ResultSet rs= conn.createStatement().executeQuery(query);
if (rs.next()) {
System.out.println(rs.getString("TAX_RATE_ID"));
}
Unrelated, but:
conn.createStatement().executeQuery() will create a Statement instance that you can't clean up properly using close().

Why does this Query return NULL?

I have a derby users database which I query, when the user clicks login on the application.
However, when I query the users table with the parameter [user] derby returns a null Object instead of the record it ought to return.
Here is my code:
String ssql = "SELECT * FROM USERS WHERE UNAME LIKE ?";
try{
DriverManager.registerDriver(new org.apache.derby.jdbc.EmbeddedDriver());
con = DriverManager.getConnection(url);
sql = con.prepareStatement(ssql, Statement.RETURN_GENERATED_KEYS);
sql.setString(1, cbox_chooseUser.getSelectedItem().toString());
sql.executeQuery();
ResultSet rs = sql.getGeneratedKeys();
try{
while (rs.next()) {
if(rs.getString("PW").toCharArray().equals(txt_password.getPassword())){
sql.close();
con.close();
return true;
}
} catch (NPE ...) {...}
}
I tried it multiple times wit a test user with both the pw and the username set to "test"; but I always get the same error.
Why is the recordset always Null?
Thanks for your help :)
The documentation says
ResultSet getGeneratedKeys() throws SQLException
Retrieves any auto-generated keys created as a result of executing this Statement
object.
If this Statement object did not generate any keys, an empty
ResultSet object is returned.
Your select statement isn't generating any keys that's why it's returning an empty ResultSet. You aren't inserting anything hence no keys are being generated.
You can try ResultSet rs = sql.executeQuery();. It should work.
You are using it in wrong way.
The generated keys concept should be used only in the case DML of insert type query but not in the case of select query.
select simply select the rows from the table. In this case there is no chance of any keys getting generated.
In the case of insert query if any column is configured as auto increment or kind of functionality then some keys will get generated. These keys can be caught using Statement.RETURN_GENERATED_KEYS in java.
As you are using select query there is no need of using Statement.RETURN_GENERATED_KEYS.
You just modify below lines and everything will be fine.
sql = con.prepareStatement(ssql, Statement.RETURN_GENERATED_KEYS);
sql.setString(1, cbox_chooseUser.getSelectedItem().toString());
sql.executeQuery();
ResultSet rs = sql.getGeneratedKeys();
with
sql = con.prepareStatement( ssql );
sql.setString( 1, cbox_chooseUser.getSelectedItem().toString() );
ResultSet rs = sql.executeQuery();

Java: How to execute preparedStatement in jdbc with multiple parameters in sql query?

This is what I want to do:
PreparedStatement query2 =
conn.prepareStatement ("UPDATE report SET Name = ? WHERE Id = ?");
String blah = "Jane";
int id = 1;
query2.setString(1, blah);
query2.setInt(2, id);
query2.executeQuery();
But I'm getting this error:
The statement did not return a result set.
I am new to the whole jdbc world. Where am I going wrong here?
You should use executeUpdate.
"Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement."

Categories