I try the below code: once just does not work, and when make Auto incremental the primary key it works, but bring the raw doubled.
At this point I guess it' s something stupid, so if an idea, I will be grateful.
try {
String insertSQL = "INSERT INTO `news`( `title`, `date`, `description`) VALUES (?,?,?)";
PreparedStatement ps = DBUtils.getPreparedStatement(insertSQL);
ps.setString(1, n.getTitle());
ps.setString(2, n.getDate());
ps.setString(3, n.getDescription());
if (ps.executeUpdate() > 0) {
ps.executeUpdate();
System.out.println("DB updtata!");
}
} catch (ClassNotFoundException |SQLException ex) {
ex.printStackTrace();
Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
}
};
Try this in try catch block..
String insertSQL = "INSERT INTO `news`( `title`, `date`, `description`) VALUES(?,?,?)";
PreparedStatement ps = DBUtils.getPreparedStatement(insertSQL);
ps.setString(1, n.getTitle());
ps.setString(2, n.getDate());
ps.setString(3, n.getDescription());
int rs = ps.executeUpdate();
if (rs > 0) {
System.out.println("DB updated!");
}
Related
public void insertTags(Elements[] elements) {
Connection con = (Connection) DbConnection.getConnection();
try {
String sql = "insert into htmltags(source) values(?),(?),(?)";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(sql);
ps.setString(1, elements[0].toString());
ps.setString(2, elements[1].toString());
ps.setString(3, elements[2].toString());
int rs = ps.executeUpdate(sql);
System.out.println("Data inserted" + rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
is this a valid syntax for Prepared statement.
This is your problem:
int rs = ps.executeUpdate(sql);
From the JavaDoc we see that PreparedStatement#executeUpdate() does not take any parameters. The reason is that we already passed the query earlier when preparing the statement. Your code should be this:
int rs = ps.executeUpdate(); // no parameter
Also no need to cast the result of prepareStatement to PrepareStatement
To insert multiple values, I don't thing using values(?),(?),(?) is the right syntax, instead use a loop, or for better way you can use batch :
String sql = "insert into htmltags(source) values(?)";
try (PreparedStatement ps = con.prepareStatement(sql);) {
for (Elements element : elements) {
ps.setString(1, element.toString());
ps.addBatch();//Add a new batch for each Element
}
int[] result = ps.executeBatch();//Submits a batch of commands to the database
} catch (SQLException e) {
e.printStackTrace();
}
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 (?,?,?,?,?,?)");
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.
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
Please give me an idea how to execute statement to DB.
There are 2 tables(sorry for incorrect writing - it is just to give information about columns):
contractors(contractor_id, contractor_name, contract_num)
invoices(contractor_id, invoice_num, invoice_date, invoice_amount)
The 'contractor_id' in 'invoices' is a foreign key for 'contractor_id' in 'contractors'. How to insert in 'invoices'-table the following data: invoice_num, invoice_date, invoice_amount, if I have the 'contractor_name' from 'contractors'-table?
The solution which works is:
public void insertInvoiceDataByContractorName(String contractorsName, String invoiceNum, String date, float amount) {
String contrId = null;
try {
preparedStatement = connection.prepareStatement("SELECT contractor_id FROM contractors WHERE contractor_name=?");
preparedStatement.setString(1, contractorsName);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
contrId = resultSet.getString(1);
}
preparedStatement = connection.prepareStatement("INSERT INTO invoices VALUES(?, ?, ? ,?)");
preparedStatement.setString(1, contrId);
preparedStatement.setString(2, invoiceNum);
preparedStatement.setString(3, date);
preparedStatement.setFloat(4, amount);
preparedStatement.execute();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (preparedStatement != null) {preparedStatement.close();}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
I don't know how to make it correct and more simpler by using just one statement. Thank you in advance for pieces of advice.
Use
INSERT INTO invoices SELECT contractor_id, ?, ?, ? FROM contractors WHERE contractor_name=?
this will insert 1 row assuming your contractor name is unique