Delete selected row in database - java

Why is this not working for me? I keep getting the error:
java.sql.SQLException: Can not issue data manipulation statements with executeQuery().
My code:
private void speler_deleteActionPerformed(java.awt.event.ActionEvent evt) {
int row = tbl_spelers.getSelectedRow();
int SpelerID = (int) tbl_spelers.getValueAt(row, 0);
Speler speler = new Speler();
try {
DBClass databaseClass = new DBClass();
Connection connectie = databaseClass.getConnection();
// NOG ONVEILIG - WACHTEN OP DB SELECT IN DBCLASS!!!
String deleteQry = "DELETE FROM `Speler` WHERE SpelerID = " + SpelerID + ";";
ResultSet rs = databaseClass.GetFromDB(deleteQry);
} catch (SQLException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}

You have to use excuteUpdate() for delete.
Docs of excuteUpdate()
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.
Where as executeQuery()
Executes the given SQL statement, which returns a single ResultSet object.

Firstly, you need to use excuteUpdate() for the delete, and next
String deleteQry = "DELETE FROM `Speler` WHERE SpelerID = " + SpelerID + ";";
remove the semi-colon and the "`" which encloses the table name "Speler", from the query.

You need to execute you query using executeUpdate()
Also, you just need to make a slight adjustment to your String deleteQry as follows:
String deleteQry = "DELETE FROM Speler WHERE SpelerID = " + SpelerID;
Hope this helps...

executeQuery() method of jdbc is to select records, you can use executeUpdate() for update operations. Please refer to the documentation for the purpose/ intent of each method:
boolean execute()
Executes the SQL statement in this PreparedStatement object, which may
be any kind of SQL statement.
ResultSet executeQuery()
Executes the SQL query in this PreparedStatement object and returns
the ResultSet object generated by the query.
int executeUpdate()
Executes the SQL statement in this PreparedStatement object, which
must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement
that returns nothing, such as a DDL statement.

Related

Working on this Java project where I need to be able to delete data from the database on user's request

The query inside MySQL is working:
DELETE FROM f9.yoo
WHERE account_tags = '#8GGGJPUR9'
I can delete data inside MySQL, but the problem is whenever I try to remove the account_tags from my Java application, it throws an error:
java.sql.SQLSyntaxErrorException: 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 'DELETE FROM f9.yoo
WHERE account_tags = '#8GGGJPUR9'' at line 2
Here's my Java SQL query:
Statement statement = dbConnection.createStatement();
String sql = "SELECT * FROM "+databaseName+"."+tableName+";\n" +
"DELETE FROM "+databaseName+"."+tableName+"\n" +
"WHERE account_tags = '"+AccountTag+"';";
statement.executeQuery(sql);
The error isn't giving me much to work with, so I really have no idea what is wrong with the program.
Did you add the allowMultiQueries=true
If not then you can add that while you sending the connecting request to your database. So you need to append the allowMultiQueries=true in your to database URL.
Like this:
String dbUrl = "jdbc:mysql:///test?allowMultiQueries=true";
String sql = "DELETE FROM "+databaseName+"."+tableName+"\n" +
"WHERE account_tags = ?";
try (PreparedStatement statement = dbConnection.prepareStatement(sq)) {
statement.setString(1, AccountTag);
int updateCount = statement.executeUpdate();
System.out.printf("%s: %d records deleted.%n", tableName, updateCount);
}
The only thing used is the DELETE, for which one should use executeUpdate.
One definitely should use a PreparedStatement as many code checkers will give alarms otherwise. It escapes things like ', handles types of the arguments, and possible conversions, and especially is a security feature against SQL injection.
The System.out usage is bad style, better would be using a logger.
try-with-resources automatically closes the PreparedStatement even with a raised exception or break/return.
When doing both database operations, it seems better to use two (prepared) statements, as the first returns a ResultSet.
So:
String sql = SELECT * FROM "+databaseName+"."+tableName + "\n" +
"WHERE account_tags = ?";
try (PreparedStatement statement = dbConnection.prepareStatement(sq)) {
statement.setString(1, AccountTag);
try (ResultSet rs = statement.executeQuery()) {
...
}
}
Better to separate statements with an If condition :
String sql1="SELECT * FROM "+databaseName+"."+tableName;
String sql2="DELETE FROM "+databaseName+"."+tableName+" "+
"WHERE account_tags = '"+AccountTag+"';
statement.executeQuery(sql1);
statement.executeUpdate(sql2);

Execute multiple SQL statements in java

I want to execute a query in Java.
I create a connection. Then I want to execute an INSERT statement, when done, the connection is closed but I want to execute some insert statement by a connection and when the loop is finished then closing connection.
What can I do ?
My sample code is :
public NewClass() throws SQLException {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
return;
}
System.out.println("Oracle JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:orcl1", "test",
"oracle");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
return;
}
if (connection != null) {
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * from test.special_columns");
while (rs.next()) {
this.ColName = rs.getNString("column_name");
this.script = "insert into test.alldata (colname) ( select " + ColName + " from test.alldata2 ) " ;
stmt.executeUpdate("" + script);
}
}
else {
System.out.println("Failed to make connection!");
}
}
When the select statement ("SELECT * from test.special_columns") is executed, the loop must be twice, but when (stmt.executeUpdate("" + script)) is executed and done, then closing the connection and return from the class.
Following example uses addBatch & executeBatch commands to execute multiple SQL commands simultaneously.
import java.sql.*;
public class jdbcConn {
public static void main(String[] args) throws Exception{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection
("jdbc:derby://localhost:1527/testDb","name","pass");
Statement stmt = con.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String insertEmp1 = "insert into emp values
(10,'jay','trainee')";
String insertEmp2 = "insert into emp values
(11,'jayes','trainee')";
String insertEmp3 = "insert into emp values
(12,'shail','trainee')";
con.setAutoCommit(false);
stmt.addBatch(insertEmp1);
stmt.addBatch(insertEmp2);
stmt.addBatch(insertEmp3);
ResultSet rs = stmt.executeQuery("select * from emp");
rs.last();
System.out.println("rows before batch execution= "
+ rs.getRow());
stmt.executeBatch();
con.commit();
System.out.println("Batch executed");
rs = stmt.executeQuery("select * from emp");
rs.last();
System.out.println("rows after batch execution= "
+ rs.getRow());
}
}
Result:
The above code sample will produce the following result.The result may vary.
rows before batch execution= 6
Batch executed
rows after batch execution= = 9
Source: Execute multiple SQL statements
In the abscence of the schema or the data contained in each table I'm going to make the following assumptions:
The table special_columns could look like this:
column_name
-----------
column_1
column_2
column_3
The table alldata2 could look like this:
column_1 | column_2 | column_3
---------------------------------
value_1_1 | value_2_1 | value_3_1
value_1_2 | value_2_2 | value_3_2
The table alldata should, after inserts have, happened look like this:
colname
---------
value_1_1
value_1_2
value_2_1
value_2_2
value_3_1
value_3_2
Given these assumptions you can copy the data like this:
try (
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl1", "test", "oracle")
)
{
StringBuilder columnNames = new StringBuilder();
try (
Statement select = connection.createStatement();
ResultSet specialColumns = select.executeQuery("SELECT column_name FROM special_columns");
Statement insert = connection.createStatement()
)
{
while (specialColumns.next())
{
int batchSize = 0;
insert.addBatch("INSERT INTO alldata(colname) SELECT " + specialColumns.getString(1) + " FROM alldata2");
if (batchSize >= MAX_BATCH_SIZE)
{
insert.executeBatch();
batchSize = 0;
}
}
insert.executeBatch();
}
A couple of things to note:
MAX_BATCH_SIZE should be set to a value based on your database configuration and the data being inserted.
this code is using the Java 7 try-with-resources feature to ensure the database resources are released when they're finished with.
you haven't needed to do a Class.forName since the service provider mechanism was introduced as detailed in the JavaDoc for DriverManager.
There are two problems in your code. First you use the same Statement object (stmt) to execute the select query, and the insert. In JDBC, executing a statement will close the ResultSet of the previous execute on the same object.
In your code, you loop over the ResultSet and execute an insert for each row. However executing that statement will close the ResultSet and therefor on the next iteration the call to next() will throw an SQLException as the ResultSet is closed.
The solution is to use two Statement objects: one for the select and one for the insert. This will however not always work by default, as you are working in autoCommit (this is the default), and with auto commit, the execution of any statement will commit any previous transactions (which usually also closes the ResultSet, although this may differ between databases and JDBC drivers). You either need to disable auto commit, or create the result set as holdable over commit (unless that already is the default of your JDBC driver).

how to automatically update a column in another table when an insertion is made in a different column in a different table in MySql using java

private void User_combo() {
try {
String sql = "insert into asset_update(User) select (Concat(first_name), ' ', (last_name)) from user";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
String name = rs.getString("User");
jComboBox_Users.addItem(name);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
it gives me the error "can not issue data manipulation statements with executeQuery();"
can someone please help me with this? Thank you in advance
Use PreparedStatement#executeUpdate
Executes the SQL statement in this PreparedStatement object, which must be an SQL Data Manipulation Language (DML) statement, such as INSERT, UPDATE or DELETE
executeQuery() for database QUERY statement(Like select)
executeUpdate() for database UPDATE statements
update
String sql = "insert into asset_update(User) select (Concat(first_name), ' ', (last_name)) from user";
pst = conn.prepareStatement(sql);
int i = pst.executeUpdate();//since it is insert statement use executeUpdate()
if(i>0){
pst = conn.prepareStatement("Select User from asset_update");
rs = pst.executeQuery();//since it is select statement use executeQuery()
while (rs.next()) {
String name = rs.getString("User");
jComboBox_Users.addItem(name);
}
}

Update a record if ID exist else Insert values

I am trying to update a value if record exists else insert the values to database. However, that is not working. I have written the below code.
String sqlCheck = "Select * from [UAP].[dbo].[UAP_EMPLOYEE] where EMP_EMPLOYEE_ID = '"+empId+"' ";
PreparedStatement prpStatementCheck = conn.prepareStatement(sqlCheck);
prpStatementCheck.setString(1, EMP_EMPLOYEE_ID);
ResultSet rsCheck=prpStatementCheck.executeQuery();
String check=null;
while((rsCheck.next())
{
if(rsCheck.next()>0)
update statement;
else
Insert Statement;
}
setString should be used with bound variables:
Your sql string should look like this:
"Select * from [UAP].[dbo].[UAP_EMPLOYEE] where EMP_EMPLOYEE_ID = ?"
What is the version of your SqlServer?
If it is 2008 or higher, you can leverage the UPSERT command.
That condition while((rsCheck.next()) will only be executed if the employee exists.
Otherwise, that code
if(rsCheck.next()>0)
update statement;
else
Insert Statement;
is unreachable.
You could use something like that:
boolean exists = false;
while((rsCheck.next())
{
update statement;
exists = true;
}
if(!exists) insert statement;
As EMP_EMPLOYEE_ID field is an INTEGER type, use setInt rather than setString:
String sqlCheck = "Select * from [UAP].[dbo].[UAP_EMPLOYEE] where EMP_EMPLOYEE_ID = ?";
PreparedStatement prpStatementCheck = conn.prepareStatement(sqlCheck);
prpStatementCheck.setInt(1, EMP_EMPLOYEE_ID);

Get number of rows updated with PreparedStatement

How to get how many rows updated with PreparedStatement?
.getUpdateCount() returns 0.
For executeUpdate got error:
error occurred during batching: batch must be either executed or cleared
my code:
updTrans = dataSource.getConnection().prepareStatement("update...");
updTrans.setInt(1, Integer.valueOf(transaksjonstatusid));
...
updTrans.addBatch();
upd = updTrans.executeUpdate();
You should be using PreparedStatement#executeBatch() when using batches.
...
updTrans.addBatch();
upd = updTrans.executeBatch();
It returns an int[] containing update counts of each batch.
Did you try to use:
int n = preparedStatement.executeUpdate();
Here you can find some explanations on how to use a PreparedStatement.
See The Javadoc
public int executeUpdate()
throws SQLException
Executes the SQL statement in this PreparedStatement object, which must
be an SQL INSERT, UPDATE or DELETE
statement; or an SQL statement that
returns nothing, such as a DDL
statement.
Returns:
either (1) the row count for INSERT, UPDATE, or DELETE statements
or (2) 0 for SQL statements that return nothing
Throws:
SQLException - if a database access error occurs or the SQL
statement returns a ResultSet object
getUpdateCount is meant to be used with the execute(String sql) method. You are probably doing this:
String sql = "UPDATE some_table SET somecolumn = ? WHERE someId = ?";
PreparedStatement ps = connection.prepare(sql);
ps.setString(1, val);
ps.setInt(2, id);
ps.executeUpdate();
In that case you should simply do
int rowsUpdated = ps.executeUpdate();

Categories

Resources