PreparedStatement resource leak while preparing a statement [duplicate] - java

This question already has answers here:
Possible resource leak when reusing PreparedStatement?
(5 answers)
Closed 6 years ago.
I suspect this may be a false positive, but I can't be sure, so I'm somewhat confused. I'm using Eclipse Neon and the issue is appearing at the third time I prepare a statement. I do something almost identical down below, with no errors.
try{
Connection con = MySQL.connection;
PreparedStatement ps = con.prepareStatement("SELECT * from UsernameData "
+ "WHERE UUID = '" + player.getUniqueId() + "'");
ResultSet rs = ps.executeQuery();
if(rs.next() == true){
ps = con.prepareStatement("update UsernameData set UUID = ?, Username = ? where UUID = ?");
ps.setString(1, uuid);
ps.setString(2, username);
ps.setString(3, uuid);
ps.execute();
ps.close();
rs.close();
return;
}
ps = con.prepareStatement("insert into UsernameData(UUID, Username)"
+ " values (?, ?)");
ps.setString(1, uuid);
ps.setString(2, username);
ps.execute();
ps.close();
rs.close();
return;
}catch(SQLException e){
Bukkit.getServer().getLogger().warning("SQL Error: " + e);
}

You don't close the first set of resources when you stomp on the ps for your insert.
You should also consider using try-with-resources:
try (Connection con = MySQL.connection;
PreparedStatement ps = con.prepareStatement("SELECT * from UsernameData "
+ "WHERE UUID = '" + player.getUniqueId() + "'");
PreparedStatement ps2 = con.prepareStatement("update UsernameData set UUID = ?, Username = ? where UUID = ?");
PreparedStatement ps3 = con.prepareStatement("insert into UsernameData(UUID, Username)"
+ " values (?, ?)");
ResultSet rs = ps.executeQuery()) {
if (rs.next() == true) {
ps2.setString(1, uuid);
ps2.setString(2, username);
ps2.setString(3, uuid);
ps2.execute();
return;
}
ps3.setString(1, uuid);
ps3.setString(2, username);
ps3.execute();
return;
} catch (SQLException e) {
Bukkit.getServer().getLogger().warning("SQL Error: " + e);
}
Yes, the second and third PreparedStatement are potentially wasted. You could wrap them in its own try-with-resources if you like.
But the crux of the problem is your stomping on the ps variable.

Related

How to call H2 LINK_SCHEMA?

I'm trying to run link_schema
final String query = "? = CALL LINK_SCHEMA('ROADS', '', '" + url + "', '" + user + "', '" + pass + "', 'ROADS');";
CallableStatement statement = conn.prepareCall(query);
statement.execute();
ResultSet rs = statement.getResultSet();
I'm getting a ResultSet but it doesn't contain the list of tables as promised. Also later when I try to access a table I get the error "Schema not found". Where did I go wrong?
Update: The problem seems to be the Oracle driver; check the answer and comment section by Evgenij Ryazanov.
You need to use
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("CALL LINK_SCHEMA(…)");
or more secure and safe
PreparedStatement ps = con.prepareStatement("CALL LINK_SCHEMA(?, '', ?, ?, ?, ?)");
ps.setString(1, "ROADS");
ps.setString(2, url);
ps.setString(3, user);
ps.setString(4, pass);
ps.setString(5, "ROADS");
ResultSet rs = ps.executeQuery();
Simple test case:
try (Connection c1 = DriverManager.getConnection("jdbc:h2:mem:1");
Connection c2 = DriverManager.getConnection("jdbc:h2:mem:2")) {
Statement s1 = c1.createStatement(), s2 = c2.createStatement();
s1.execute("CREATE SCHEMA S; CREATE TABLE S.T1(ID INT); CREATE TABLE S.T2(ID INT)");
try (ResultSet rs = s2.executeQuery("CALL LINK_SCHEMA('S', '', 'jdbc:h2:mem:1', '', '', 'S')")) {
while (rs.next()) {
System.out.println(rs.getString(1));
}
}
}
T1
T2

how to pass the id value using name from one table to another table and store the information to database [duplicate]

This question already has answers here:
java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0) [closed]
(2 answers)
Closed 4 years ago.
Sql query how to pass the id from department table using the department name to the user table using the department id
here in department table dept_id is primary key
and dept_id in user table is foreign key
how to select the dept_id using department_name from the department table and store the value in the user table
try{
Connection con = DBconnect.getConnection();
//selecting the dpartment
String sql ="select DEPARTMENT_CODE,DEPARTMENT_NAME from department_info";
PreparedStatement ps = con.prepareStatement(sql);
String s11=comboboxdeptid.getItems().toString();
ResultSet rs=ps.executeQuery();
if(rs.next()==true)
{
if(rs.getString("DEPARTMENT_NAME").equals(comboboxdeptid.getSelectionModel().toString()))
rs.getString("DEPARTMENT_CODE");
}
//second stmt
String sql1 = "insert into user_info(USER_NAME, FIRST_NAME, LAST_NAME, DESIGNATION, ADDRESS,PASSWORD_TXT,DEPARTMENT_CODE,CREATED_BY) values(?,?,?,?,?,?,?,?)";
PreparedStatement ps1 = con.prepareStatement(sql1);
String s12 = nameid.getText();
String s13 = Firstnameid.getText();
String s14 = Lnameid.getText();
String s15 = desigid.getText();
String s16 = comboboxdeptid.getItems().toString();
String s17 = addrsid.getText();
String s18 = passwordid.getText();
ps.setString(1, s12);
ps.setString(2, s13);
ps.setString(3, s14);
ps.setString(4, s15);
ps.setString(5, s17);
ps.setString(6, s18);
ps.setString(7, s11);
ps.setString(8, "abc");
ps.execute();
ResultSet rs1=ps1.executeQuery();
//third stmt
String sql2 = "update security_qa_info set SECURITY_QUESTION=?, SECURITY_ANSWER=? where USER_ID=?";
PreparedStatement ps2 = con.prepareStatement(sql2);
String s19 = securityquestionid.getSelectionModel().getSelectedItem().toString();
String s20 = answerid.getText();
while(rs2.next()==true)
{
if(rs2.getString("USER_NAME").equals(nameid.getText()))
{
rs2.getString("USER_ID");
ps2.setString(1, s16);
}
}
ps2.setString(2, s19);
ps2.setString(3, s20);
ps2.executeUpdate();
showMessageDialog(null, "Registration Successful");
}catch(Exception e){
// showMessageDialog(null, e);
e.printStackTrace();
}
Parent fxml = FXMLLoader.load(getClass().getResource("/com/abc/fxml/LoginPage.fxml"));
pane2.getChildren().setAll(fxml);
} else {
showMessageDialog(null, "Passwords don't match!");
}
}
ps = prepared statement for SELECT query:
String sql ="select DEPARTMENT_CODE,DEPARTMENT_NAME from department_info";
PreparedStatement ps = con.prepareStatement(sql);
ps1 = prepared statement for INSERT statement:
String sql1 = "insert into user_info(USER_NAME, FIRST_NAME, LAST_NAME, DESIGNATION, ADDRESS,PASSWORD_TXT,DEPARTMENT_CODE,CREATED_BY) values(?,?,?,?,?,?,?,?)";
PreparedStatement ps1 = con.prepareStatement(sql1);
Using the wrong prepared statement:
ps.setString(1, s12);
A suggestion - if you call the first prepared statement 'selectDepartmentDetails' and the second 'insertUserInfo', it is less likely you will run into this.

java.sql.sqlexception invalid column index

Hello everyone can someone tell me what is wrong here ?
I have a task i was asked and i am new in connecting oracle databases with java servlet.
here is me code:
try {
out.print("first");
Class.forName("oracle.jdbc.OracleDriver");
out.print("aaa");
Connection con
= DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:xe", "myusername", "mypassword");
out.print("111");
PreparedStatement ps = con
.prepareStatement(
"INSERT INTO signup
values(fn, ln, date, em, pa, crnum)
");
out.print("222");
ps.setString(1, fn);
ps.setString(2, ln);
ps.setString(3, da);
ps.setString(4, em);
ps.setString(5, pa);
ps.setString(6, cr);
int i = ps.executeUpdate();
if (i > 0) {
out.print("You are successfully registered...");
}
} catch (Exception e2) {
out.println(e2);
}
out.close();
response.sendRedirect("address");
/* when press next bottom
it'll take me to add.html*/
and after i ran the whole code i get this :java.sql.sqlexception: invalid column index
In your SQL statement, you have to provide the tokens or placeholders for your bind variable like in the following...
PreparedStatement ps = con.prepareStatement("INSERT INTO signup values(?,?,?,?,?,?)");
ps.setString(1,fn);
ps.setString(2,ln);
ps.setString(3,da);
ps.setString(4,em);
ps.setString(5,pa);
ps.setString(6,cr);
You need to use placeholder ?:
PreparedStatement ps = con.prepareStatement("INSERT INTO signup values (?,?,?,?,?,?)");

SQL Exception . update row in jdbc

I need to write a query to update a row in the database. but exception is
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Erreur de syntaxe pr?s de 'SET eMail = '11111', SET phoneNumber = '111111' WHERE name = 'Saba', surname= 'M' ? la ligne 1 .
what is the problem?
public static void updateUser(User user, Connection connection) throws SQLException {
PreparedStatement ps = null;
ps = connection.prepareStatement("UPDATE USERS SET login = ?, SET eMail = ?, SET phoneNumber = ? WHERE name = ?, surname= ?");
ps.setString(1, user.getLogin());
ps.setString(2, user.geteMail());
ps.setString(3, user.getPhoneNumber());
ps.setString(4, user.getName());
ps.setString(5, user.getSurname());
ps.executeUpdate();
The UPDATE statement only has a single SET clause. You repeated the SET keyword, which is wrong. Besides, you forgot the AND keyword to combine predicates. Write this instead:
try (PreparedStatement ps = connection.prepareStatement(
"UPDATE USERS "
+ "SET login = ?, eMail = ?, phoneNumber = ? "
+ "WHERE name = ? AND surname = ?")) {
// ...
}

column not allowed here oracle with getText

I tried to save / edit / delete a new row in the database. writing in the gui values to be saved with getText ()
here is the code
Connection conn = Connessione.ConnecrDb();
Statement stmt = null;
ResultSet emps = null;
try{
String sql;
sql = "INSERT INTO PROGETTO.LIBRO (ISBN, DISPONIBILITA, TITOLO, CASA_EDITRICE, CODICE_AUTORE, GENERE, PREZZO)"
+ "VALUES (txt_isbn, txt_disp, txt_titolo, txt_casa, txt_autore, txt_genere, txt_prezzo)";
stmt = conn.createStatement();
emps = stmt.executeQuery(sql);
String ISBN= txt_isbn.getText();
String DISPONIBILITA= txt_disp.getText();
String TITOLO= txt_titolo.getText();
String CASA_EDITRICE= txt_casa.getText();
String CODICE_AUTORE= txt_autore.getText();
String GENERE= txt_genere.getText();
String PREZZO = txt_prezzo.getText();
JOptionPane.showMessageDialog(null, "SALVATO");
}catch(SQLException | HeadlessException e)
{
JOptionPane.showMessageDialog(null, e);
}
finally
{
try{
if (emps != null)
emps.close();
}
catch (SQLException e) { }
try
{
if (stmt != null)
stmt.close();
}
catch (SQLException e) { }
}
Getting this error: column not allowed here
Above code just takes care of insert operation. How can I delete and modify table record?
You have asked 2 different questions here
1. Column not allowed here
This happened because you have not passed values for any of parameter into insert statement.
I am not sure about your requirement however I will use PreparedStatement for this scenario.
Example
String insertTableSQL = "INSERT INTO DBUSER"
+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
+ "(?,?,?,?)";
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertTableSQL);
preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "MindPeace");
preparedStatement.setString(3, "system");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
preparedStatement .executeUpdate();
2. This code is only to save the data, delete, and modify an entire row how can I do?
Answer is very simple. You have to write code for the same :)
You need 3 SQL statement which has DELETE and UPDATE operation just like insert in above example.
String sql = "INSERT INTO PROGETTO.LIBRO (ISBN, DISPONIBILITA, TITOLO, "
+ "CASA_EDITRICE, CODICE_AUTORE, GENERE, PREZZO)"
+ "VALUES (?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement stmt = conn.createStatement()) {
NumberFormat numberFormat = NumberFormat.getInstance(Locale.ITALY);
String ISBN = txt_isbn.getText();
String DISPONIBILITA = txt_disp.getText();
String TITOLO = txt_titolo.getText();
String CASA_EDITRICE = txt_casa.getText();
String CODICE_AUTORE = txt_autore.getText();
String GENERE = txt_genere.getText();
BigDecimal PREZZO = new BigDecimal(
numberFormat.parse(txt_prezzo.getText()).doubleValue())
.setScale(2);
stmt.setString(1, ISBN);
stmt.setString(2, DISPONIBILITA);
stmt.setString(3, TITOLO);
stmt.setString(4, CASA_EDITRICE);
stmt.setString(5, CODICE_AUTORE);
stmt.setString(6, GENERE);
stmt.setBigDecimal(7, PREZZO);
int updateCount = stmt.executeUpdate();
JOptionPane.showMessageDialog(null, "SALVATO");
} catch(SQLException | HeadlessException e) {
JOptionPane.showMessageDialog(null, e);
}
Try-with-resources closes the stmt automatically.
The prepared statement replaces the value in the SQL with something like:
INSERT INTO table(column1, colum2, ....)
VALUES('De\'l Rey',
1234.50,
...)
for:
"De'l Rey"
1.234,50
updateCount should be 1 on success.
Wooow..true!!
I created three buttons to delete / update / insert and now it all works and automatically updates the tables.
you've been very very great. Thank you very much.
one last thing.
if I wanted to insert an error message when I delete / update etc "book not found" I tried to create an if:
Boolean found = false;
try{
sql= delete......
etc
if (!found)
JOptionPane.showMessageDialog(null, "NOT FOUND","ERRORE",JOptionPane.WARNING_MESSAGE);
etc...
Connection conn = Connessione.ConnecrDb();
Statement stmt = null;
ResultSet emps = null;
try{
String sql= "DELETE FROM progetto.libro WHERE isbn =?"; /
pst=(OraclePreparedStatement) conn.prepareStatement(sql);
pst.setString (1, txt_isbn.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "ELIMINATO");
Update_table();
txt_isbn.setText("");
txt_disp.setText("");
txt_titolo.setText("");
txt_casa.setText("");
txt_autore.setText("");
txt_genere.setText("");
txt_prezzo.setText("");
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
if you find the book must exit the book removed, or "not found". but as I deployed I always come out "deleted". why?
thanks again

Categories

Resources