I'm trying to update the record in my MySql database using JDBC.
Here is the method:
public void updateGareCorse(CorrePer c) {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = DBConnectionPool.getConnection();
String sql = "update corre_per set gare_corse = ?\n"
+ " where codice_pilota = ? and anno = ?";
ps = con.prepareStatement(sql);
ps.setString(1, c.getGare_corse());
ps.setString(2, c.getCodice());
ps.setInt(3, c.getAnno());
System.out.println("QUERY:\nUPDATE corre_per SET gare_corse = " + c.getGare_corse()+" WHERE anno = "+ c.getAnno() +" AND codice_pilota = " + c.getCodice()+")");
int result = ps.executeUpdate(sql);
if (result > 0) {
System.out.println("Update OK");
} else {
System.out.println("Update NOT OK");
}
con.commit();
} catch (SQLException s) {
System.err.println(s.getMessage());
Utility.printSQLException(s);
} finally {
try {
if (rs != null)
rs.close();
if (ps != null)
ps.close();
DBConnectionPool.releaseConnection(con);
} catch (SQLException s) {
System.err.println(s.getMessage());
Utility.printSQLException(s);
}
}
}
CorrePer is a Java class that represents my CorrePer table and has variables that represent my CorrePer attributes and their getter and setter method.
Now, when I execute this method, Eclipse gives this error:
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 '? where codice_pilota = ? and anno = ?' at line 1
Why the method doesn't work? Any help is much appreciated.
UPDATE: I tried to pass only one parameter at a time, with the others not being parametric, but already written in the query, like this:
String sql = "update corre_per set gare_corse = \"1-\"\n"
+ " where codice_pilota = \"TSU\" and anno = ?";
ps = con.prepareStatement(sql);
//ps.setString(1, c.getGare_corse());
//ps.setString(1, c.getCodice());
ps.setInt(1, c.getAnno());
Now it gives error only on the '?' at the end:
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 '?' at line 2
So looks like there is a problem with the parameters association, but I'm not able to figure out it.
Here is your problem
int result = ps.executeUpdate(sql);
Just use (as you already set your parameter values)
int result = ps.executeUpdate();
Otherwise actual call is delegated to java.sql.Statement.executeUpdate(String) which perform SQL udpate as-is (without interpolation of arguments, so ? tokens in your parametrized query are not replaced with supplied values)
In an database application, while testing an update button statements for some application jtable which represents a database table contents, i gained a resulting behavior with either creating a new row/record or throwing an duplicate primary key exception such being the same row/record key, with a clear update statement and syntax, actually i asked here before and i was guided to provide a "Minimal, Complete, and Verifiable example" , so i grabbed those updating lines in a new java runnable class - which worked very well and i didn't notice the difference - and it was such this counterpart parameters code example :
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class QueryTesting
{
public static void main(String[] args)
{
try
{
// create a java mysql database connection
Class.forName("com.mysql.jdbc.Driver");
try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/?verifyServerCertificate=false&useSSL=true", "username", "password")) {
Statement s = null ;
try {
s = conn.createStatement();
} catch (SQLException ex) {
Logger.getLogger(QueryTestingForWMC.class.getName()).log(Level.SEVERE, null, ex);
}
int Result ;
try {
Result = s.executeUpdate("USE myDatabase");
} catch (SQLException ex) {
Logger.getLogger(QueryTestingForWMC.class.getName()).log(Level.SEVERE, null, ex);
}
PreparedStatement preparedStmt= null;
// create the java mysql update preparedstatement
String query = "update relativesTable set idRelativeMembers = ? , Name = ? , Picture = ? , RelationDegree = ? , persons_idPersons = ? where idRelativeMembers = ?";
// create the mysql update preparedstatement
preparedStmt = conn.prepareStatement(query);
preparedStmt.setString(1,"00002/10");
preparedStmt.setString(2,"عبد الحفيظ أحمد عبد الفتاح الدؤري");
preparedStmt.setBinaryStream(3, null);
preparedStmt.setString(4, "إبن عم");
preparedStmt.setString(5, "00002");
preparedStmt.setString(6, "00002/10");
// execute the java preparedstatement
preparedStmt.executeUpdate();
preparedStmt.close();
s.close();
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}catch (ClassNotFoundException e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
the update code block - in the original application - mentioned with a System.out.println() hint statement to assure that is the updating statement conditional block :
// the mysql update statement
String selectedMemberPrimaryKey = getMembersWithoutPhotos().get(jTable5.convertRowIndexToView(jTable5.getSelectedRow())).getId() ;
System.out.println("This is an update query");
String updateStatement = "update relativesTable set idRelativeMembers = ? , Name = ? , Picture = ? , RelationDegree = ? , persons_idPersons = ? where idRelativeMembers = ?";
// create the mysql update preparedstatement
preparedStmt = conn.prepareStatement(updateStatement);
preparedStmt.setString(1, jTextField2.getText());
while insert condition is hinted also with an insertion hint :
// the mysql insert statement
System.out.println("This is an insert query");
String insertStatement = "insert into relativesTable (idRelativeMembers, Name, Picture, RelationDegree, persons_idPersons) values ( ?, ?, ?, ?, ?)";
// create the mysql insert preparedstatement
preparedStmt = conn.prepareStatement(insertStatement);
preparedStmt.setString(1, jTextField2.getText());
The database table is related with another table through persons_idPersons foreign key, till now, i cannot figure out how the behavior would came from, however, is there is a condition(s) that may leads to the insertion behavior for the jdbc sql update statement ?
NEW NOTION :
I have tried to prepare the update query by other prepare statement way such :
System.out.println("This is an update query");
String updateStatement = "update relativesTable set idRelativeMembers = '00002/20' , Name =' أحمد عبد البارئ الثبنيتي ', Picture = null , RelationDegree =' عم ', persons_idPersons = '00002' where idRelativeMembers = '00002/10'";
// create the mysql update preparedstatement
preparedStmt = conn.prepareStatement(updateStatement);
and it has worked very well !
The whole UPDATE statement block in the jbutton for saving data to the database is - while i have commented the whole INSERT statement block in the jbutton, and still UPDATE works in such INSERT behavior! - :
try
{
// the mysql update statement
String selectedRelateivesMemberPrimaryKey = getMembersWithoutPhotos().get(jTable5.convertRowIndexToView(jTable5.getSelectedRow())).getId() ;
System.out.println("This is an update query");
String updateStatement = "update relativesTable set idRelativeMembers = ? , Name = ? , Picture = ? , RelationDegree = ? , persons_idPersons = ? where idRelativeMembers = ?";
// create the mysql update preparedstatement
preparedStmt = conn.prepareStatement(updateStatement);
preparedStmt.setString(1, jTextField2.getText());
selectedRelativeMemberForUpdateId = jTextField2.getText();
preparedStmt.setString(2, jTextField4.getText());
if(null == jLabel17.getIcon())
{
preparedStmt.setBinaryStream(3, null);
}else
{
Icon icon = jLabel17.getIcon();
ImageIcon img = (ImageIcon) icon ;
BufferedImage bI = new BufferedImage(img.getIconWidth(), img.getIconHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = bI.createGraphics();
icon.paintIcon(null, g, 0,0);
g.dispose();
ImageIO.write(bI, "jpg", new File("personRelativeMemTempImage.jpg"));
personRelativeMemImageFileForDatabase = new File("personRelativeMemTempImage.jpg");
personRelativeMemImageFileInputStream = new FileInputStream(personRelativeMemImageFileForDatabase);
preparedStmt.setBinaryStream(3,(InputStream) personRelativeMemImageFileInputStream,(int) personRelativeMemImageFileForDatabase.length());
}
preparedStmt.setString(4, jTextField15.getText());
preparedStmt.setString(5, selectedPersonForRelativeMembersId);
preparedStmt.setString(6, selectedRelateivesMemberPrimaryKey);
// execute the preparedstatement
preparedStmt.execute();
try {
preparedStmt.close();
} catch (SQLException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
catch (FileNotFoundException | SQLException e)
{
System.err.println("Got an exception!");
System.err.println(e.getMessage());
String exceptionMessage = e.getMessage();
if(exceptionMessage.contains(exceptionStringPartOne) && exceptionMessage.contains(exceptionStringPartTwo))
{
JOptionPane.showMessageDialog(null, "Duplicate Keys","error",JOptionPane.ERROR_MESSAGE);
duplicatePrimaryKeyFlag = true ;
}else
{
JOptionPane.showMessageDialog(null, "A Related Database Error","error",JOptionPane.ERROR_MESSAGE);
return;
}
} catch (IOException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
No, you need an INSERT statement to insert a new row, an UPDATE will only act on an existing record.
There is a possibility that there is an before/after UPDATE trigger defined on the table that does the INSERT but it would still be an INSERT that creates the new record, however it is called.
You could check for a trigger with
select * from `information_schema`.`triggers`
where event_object_schema = 'myDatabase'
and event_object_table = 'relativesTable'\G
However, a more likely explanation is an error in your application logic that runs the insert path rather than the update path, or both.
Preamble :
The application form was providing a selection to a person from person's jtable and then other selection to his/her relatives members from relatives jtable, and the other selection which is to a relative member brings members's row data to jtextfields to be modified and saved by a save button, and what was happening is throwing duplicate primary key exception in case of updating a member data with the same key, and in case of entering new id for key, a new member appears in the member's jtable.
Behind the Behavior :
Regardless of the state of affairs of writting this application, the problem was in superfluous using of methods at this line :
String selectedMemberPrimaryKey = getMembersWithoutPhotos().get(jTable5.convertRowIndexToView(jTable5.getSelectedRow())).getId() ;
it was enough to retrieve the key of the relatives members jtable to update the corresponding keyed record in the relatives members database table through the id column with just :
String selectedMemberPrimaryKey = jTable5.getValueAt(jTable5.convertRowIndexToView(jTable5.getSelectedRow()), 0).toString();
, and this mismatch led to retrieve another key and specify another record to be updated with the relative member's updating data. Thus, updating the wrong record (key column, and other columns) with the desired record data leads to duplicate primary key exception, and in case of updating the wrong record with a new data of a new relative member for a person, the new record appears in the the desired person's members jtable, which was the update of a member from another - wrong - person's members.
So, in an java/mysql application, an sql UPDATE cannot behave directly as an sql INSERT, but it may leave an INSERT effects as in this case if this wrong updated record was auto-renewable or auto-recreatable, so it would leave some INSERT behavior.
Thank you all For caring, viewing and trying to answer.
Hi I have a problem with my syntax in my java code. I have a tableview which gets its data from a SQL database. I have created 3 tables in the database book, customer, order. When I click a button I want to take the selected books and add them to the order table.
Here is the code from the main program (calling the method from db):
if(table.getSelectionModel().getSelectedItems().iterator().hasNext()) {
db.insertOrder(new Bestellung(customerid,table.getSelectionModel().getSelectedItems().iterator().next()));
The table book is fixed. Just the two other tables customer,order are dynamic.
The problem:
I create the values in the order table like this
String ct = "CREATE TABLE Order (" + "Order_Id integer generated always as identity, " + "CUSTOMER_ID BIGINT" + "ISBN, CHAR(13) " + "PRIMARY KEY(Order_Id))";
and so on...
I insert into order table like this. (Here is the syntax problem in the String i That's the position where the compiler says it doesn't work..)
String i = "INSERT INTO ORDER(CUSTOMER_ID,ISBN), VALUES(?,?)";
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DriverManager.getConnection(connString);
stmt = conn.prepareStatement(i);
conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
stmt.setLong(1, order.getCustomerId());
stmt.setString(2, order.getBuch().getISBN());
stmt.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
finally {
try {
if (stmt != null)
stmt.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
and here is the syntax error which I got
Syntax error: Encountered "ORDER" at line 1, column 13.
So how do I have to correct my syntax in the string i? Does anyone have any ideas?
INSERT INTO ORDER(CUSTOMER_ID,ISBN), VALUES(?,?)
^
The comma is superfluous. Also, in your CREATE TABLE
... + "ISBN, CHAR(13) " + ...
^
This comma is also extraneous.
If you want to use reserved words/keywords as Table name, you should:
MySQL: use ' , like : select * from 'Order'
Oracle, PostgreSQL: use " , like : select * from "Order"
But it is bad practice, try to change your table name.
You have another Error that answered by #Jim Garrison.
ok iam having a problem i need to delete all columns that start with ? on primery key ex.?5 ,?4 i amm running this throw a java app i have build so i need the java query that search my database ektupotiko and then delete all columns that start with ? on primary key
here is my try but it doesnt work any idea how i can make it work ?
public void mix(){
String queryy ="DELETE FROM ektupotiko WHERE Αριθμος_ΔΔΥ = ?% ");
executeSQLQueryy(queryy,"updated");
}
public void executeSQLQueryy (String queryy,String message) {
Connection con =getConnection();
Statement st;
try{
st =con.createStatement();
if((st.executeUpdate(queryy))==1)
{
con.commit();
// DefaultTableModel model=(DefaultTableModel)jTable_ProSales.getModel();
// model.setRowCount(0);
//show_Basket_in_Jtable();
JOptionPane.showMessageDialog(null,"Data "+message+" Succefully");
}else{
JOptionPane.showMessageDialog(null,"Data "+message+ " Succefully");
}
}catch (Exception ex){
ex.printStackTrace();
}}
Your query is looking for equality and also is missing some quotes, try with a LIKE clause :
String queryy = "DELETE FROM ektupotiko WHERE Αριθμος_ΔΔΥ LIKE '?%' ";
Use like :
String queryy ="DELETE FROM ektupotiko WHERE Αριθμος_ΔΔΥ like '?%' ";
executeSQLQueryy(queryy, "updated");
I'am new to java, this question may have been asked earlier but I'm not getting the exact answer.I want to add data from database into at and display it through jsp. But empty or null values is shown i.e no data is being displayed and when I execute the same sql query which is used in code in sql server ,then required output is displayed.
My java code is:
public List < Alarm_Bean > get_Count(String system_Name)
{
if (system_Name.equals("MPS"))
{
try {
con = getConnection();
stmt = con.createStatement();
String sql = " select system_name,COUNT(distinct arrival_time) AS c from i2alarmlog where Ack_status=0 AND Direction='CAME' and system_name in( 'I2-tciu database','i2-mps database') group by system_name union all select 'sum' system_name, Count(distinct arrival_time) from i2alarmlog where Ack_status=0 AND Direction='CAME' and system_name in( 'I2-tciu database','i2-mps database') ";
stmt.executeQuery(sql);
rs = stmt.getResultSet();
while (rs.next()) {
Alarm_Bean obj = new Alarm_Bean();
obj.setSystem_name(rs.getString("system_name"));
obj.setC(rs.getString("c"));
at.add(obj);
}
} catch (Exception e) {
System.out.println("\nException " + e);
} finally {
closeConnection(stmt, rs, con);
}
}
//System.out.println(at);
return at;
}
Jsp code is:-
<c:out value="${ab.get_Count(MPS)}"></c:out>