How make a update using java netbeans and sqlservel - java

I want to make a CRUD in netbeans and sqlserver,I have already learnt how make the inserts and deletes but I haven't abled to solve the update.Help me please.
These are my codes:
name database abarrotes, table producto.
Method update:
public void ModificarProducto (Producto c){
try{
con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/abarrotes", "root", "123");
String sentencia = "UPDATE producto SET Nombre_Producto= ?, Marca_Producto = ?, Presentacion_Producto=?, Precio_Producto=?, Punto_de_Reorden = ?, Existencia = ? where Id_Producto=?;";
PreparedStatement pstm = con.prepareStatement(sentencia);
pstm.setInt(1, c.getId_Producto());
pstm.setString(2, c.getNombre_Producto());
pstm.setString(3, c.getMarca_Producto());
pstm.setString(4, c.getPresentacion_Producto());
pstm.setFloat(5, c.getPrecio_Producto());
pstm.setInt(6, c.getPunto_de_Reorden());
pstm.setInt(7, c.getExistencia());
pstm.execute();
pstm.close();
} catch(SQLException e){
System.out.println(e);
}
}
The frame's boton
OperacionesProducto basedatos = new OperacionesProducto();
private void Btn_InsertarActionPerformed(java.awt.event.ActionEvent evt) {
Producto prod = new Producto();
prod.setId_Producto(Integer.parseInt(Id_Producto.getText()));
prod.setNombre_Producto(Nombre_Producto.getText());
prod.setMarca_Producto(Marca_Producto.getText());
prod.setPresentacion_Producto(Presentacion_Producto.getText());
prod.setPrecio_Producto(Float.parseFloat(Precio_Producto.getText()));
prod.setPunto_de_Reorden(Integer.parseInt(Punto_de_Reorden.getText()));
prod.setExistencia(Integer.parseInt(Existencia.getText()));
basedatos.InsertarProducto(prod);
}
DOESN'T MARK ANY ERROR BUT THE DATABASE DOESN'T CHANGE
HELP ME PLEASE :).

The order of the ? in the query string doesn't match the indexes of the set commands. I think the first needs to be last and everything else moved up one to make all the names match. Change to:
String sentencia = "UPDATE producto SET "
+ "Nombre_Producto= ?, "
+ "Marca_Producto = ?, "
+ "Presentacion_Producto=?, "
+ "Precio_Producto=?, "
+ "Punto_de_Reorden = ?, "
+ "Existencia = ? "
+ "where Id_Producto=?;";
PreparedStatement pstm = con.prepareStatement(sentencia);
pstm.setString(1, c.getNombre_Producto());
pstm.setString(2, c.getMarca_Producto());
pstm.setString(3, c.getPresentacion_Producto());
pstm.setFloat(4, c.getPrecio_Producto());
pstm.setInt(5, c.getPunto_de_Reorden());
pstm.setInt(6, c.getExistencia());
pstm.setInt(7, c.getId_Producto());

Related

Java Prepared Statement Cannot Update Database

I am using the prepared statement to store some variables into the database. The program runs without any errors but the database wont update.
public void setData(Dealer sDealer)
{
String fName = sDealer.getFirstName();
String lName = sDealer.getLastName();
int age = sDealer.getAge();
int xp = sDealer.getExperience();
String mStatus = sDealer.getMartialStatus();
String dAdd = sDealer.getAddress();
String pNum = sDealer.getPhoneNumber();
String email = sDealer.getEmailAddress();
String crime = sDealer.getCriminalRecord();
String type = sDealer.getCategory();
String SQL ="INSERT INTO DEALERS ("
+"firstName, " +"lastName ," +"dAge, "
+"dXp, " +"maritalStatus , " +"dAddress, "
+"phoneNumber, " +"dMail, " +"criminalRecord, " +"dType )"
+"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
try{
My suspicion is on the following prepared statement I used in this method but I am unable to figure out just what I am doing wrong.
PreparedStatement pStat = dConnect.prepareStatement(SQL);
pStat.setString(1, fName);
pStat.setString(2, lName);
pStat.setInt(3, age);
pStat.setInt(4, xp);
pStat.setString(5, mStatus);
pStat.setString(6, dAdd);
pStat.setString(7, pNum);
pStat.setString(8, email);
pStat.setString(9, crime);
pStat.setString(10, type);
}catch(Exception sx){
System.out.println("Error is found :"+sx);
}
}
You need to execute the statement and commit these database changes by adding lines in try-catch block:
pStat.executeUpdate();
dConnect.commit();
You just need to execute the statement by adding one additional call:
pStat.executeUpdate();

Syntax error in update query near '? in eclipse but working in MySQL workbench

I'm getting this error in eclipse
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 '? , login = ? , pwd = ? WHERE login = 'pp'' at line 1
This is my query in my source code:
String query2 = "UPDATE usuarios SET nombre = ? , login = ? , pwd = ? WHERE login = '" + login2 + "'";
And this is the whole code from my method:
private void modificar() {
// Prints the content of the table
String query = "SELECT * FROM usuarios";
try {
pst = con.Conectar().prepareStatement(query);
rs = pst.executeQuery(query);
// Itarate over the registries
int i = 0;
while (rs.next()) {
i++;
//print them
System.out.println(i + " " + rs.getString("id") + " " + rs.getString("login"));
}
//There are X registries
System.out.println("Existen " + i + " usuarios actualmente");
pst.close();
//Wich registry do you need to modify?
System.out.println("Ingrese el login del usuarios a modificar");
String login2 = scanner.nextLine();
System.out.println("Ingrese datos a modificar");
System.out.print("Nombre: ");
nombre = scanner.nextLine();
System.out.print("Login: ");
login = scanner.nextLine();
System.out.print("Password: ");
pwd = scanner.nextLine();
String query2 = "UPDATE usuarios SET nombre = ? , login = ? , pwd = ? WHERE login = '" + login2 + "'";
pst = con.Conectar().prepareStatement(query2);
pst.setString(1, nombre);
pst.setString(2, login);
pst.setString(3, pwd);
/*
* Aqui da error de sintaxis en query2
*/
pst.executeUpdate(query2);
pst.close();
String query3 = "SELECT * FROM usuarios where login =" + login;
pst = con.Conectar().prepareStatement(query3);
rs = pst.executeQuery(query3);
rs.next();
System.out.println("ahora quedo asi " + rs.getString("login"));
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
} finally {
cerrarConsultas();
}
}
But is working fine when I use it in MySQL Workbench, this is my test in the workbench.
prepare insertar from "UPDATE usuarios SET nombre = ?, login = ?, pwd = ? WHERE login = 'pp'";
-- "UPDATE usuarios SET nombre = ?, login = ?, pwd = ? WHERE login = 'pablo'";
set #nombre = 'pp';
set #login = 'pp';
set #pwd = 'pp';
execute insertar using #nombre, #login, #pwd;
deallocate prepare insertar;
I've tried even with literal qoutes and still doesn't work.
String query2 = "UPDATE usuarios SET `nombre` = ? , `login` = ? , `pwd` = ? WHERE login = '" + login2 + "'";
Also tried:
String query2 = "UPDATE usuarios SET `nombre` = ? , `login` = ? , `pwd` = ? WHERE login = "+ login2;
Same result.
Replace
pst.executeUpdate(query2);
with
pst.executeUpdate();
Otherwise you will end up ignoring the parameter binding you did with with the various pst.setString(...) hence the db engine will receive a query with ? instead of the values you meant to bind.
Why not using a parameter for your WHERE clause?
String query2 = "UPDATE usuarios SET nombre = ? , login = ? , pwd = ? WHERE login = ?";
pst = con.Conectar().prepareStatement(query2);
pst.setString(1, nombre);
pst.setString(2, login);
pst.setString(3, pwd);
pst.setString(4, login2 );

Insert into sql server database error

I am trying to insert data into the database, but I am getting an error when I click the button insert.
This is the error
com.microsoft.sqlserver.jdbc.SQLServerException: There are more columns in the INSERT
statement than values specified in the VALUES clause. The number of values in the VALUES
clause must match the number of columns specified in the INSERT statement.
I would like your help if you can figure out the problem.
This is my insertion code
private void insertActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
dbconnection db = new dbconnection();
try {
db.connect();
db.stm=db.con.createStatement();
java.sql.Date date1 = new java.sql.Date(jDateChooser1.getDate().getTime());
int result=db.stm.executeUpdate("insert into Blood_Test_Result" +"(DID,D_Name,Weight,HBsAG,HIV,VDRL,HCV,Malaria,Blood_Type,Blood_Status,LTID,LT_Name,Date)"
+"values('"+jComboBox2.getSelectedItem().toString()+"',"
+ "'"+jTextField1.getText()+"','"+jTextField3.getText()+"','"+jComboBox4.getSelectedItem().toString()+"',"
+ "'"+jComboBox5.getSelectedItem().toString()+"','"+jComboBox6.getSelectedItem().toString()+"',"
+ "'"+jComboBox7.getSelectedItem().toString()+"','"+jComboBox8.getSelectedItem().toString()+"'"
+ "'"+jComboBox9.getSelectedItem().toString()+"','"+jComboBox10.getSelectedItem().toString()+"',"
+ "'"+jComboBox3.getSelectedItem().toString()+"','"+jTextField2.getText()+"','"+date1+"')");
if(result>0)
{
JOptionPane.showMessageDialog(this, "Data has been saved succesfully");
}
else
{
JOptionPane.showMessageDialog(this, "no data has been saved");
}
} catch (SQLException ex) {
Logger.getLogger(BloodTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
The error is clear you are using 13 column in .
(BTRID,DID,D_Name,Weight,HBsAG,HIV,VDRL,HCV,Malaria,Blood_Type,Blood_Status,LTID,LT_Name)
But you set 12 value in values :
values(....)
So check your query step by step and make sure that you are using the correct columns.
My answer is for this important part, don't set your attributes like this, instead use PreparedStatement to avoid syntax error and SQL Injection :
String query = "insert into Blood_Test_Result" + "(BTRID, DID ,D_Name, "
+ "Weight, HBsAG, HIV, VDRL, HCV, Malaria, Blood_Type, Blood_Status, LTID,LT_Name)"
+ "values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement insert = connection.prepareStatement(query)) {
insert.setString(1, jComboBox2.getSelectedItem().toString());
insert.setString(2, jTextField1.getText());
...
insert.executeUpdate();
}
The error is very clear :
You have more Columns in your statment than values!
(BTRID,DID,D_Name,Weight,HBsAG,HIV,VDRL,HCV,Malaria,Blood_Type,Blood_Status,LTID,LT_Name)
This are 13 columns and you have
jComboBox2.getSelectedItem().toString()+"',"
+ "'"+jTextField1.getText()+"','"+jTextField3.getText()+"','"+jComboBox4.getSelectedItem().toString()+"',"
+ "'"+jComboBox5.getSelectedItem().toString()+"','"+jComboBox6.getSelectedItem().toString()+"',"
+ "'"+jComboBox7.getSelectedItem().toString()+"','"+jComboBox8.getSelectedItem().toString()+"'"
+ "'"+jComboBox9.getSelectedItem().toString()+"','"+jComboBox10.getSelectedItem().toString()+"',"
+ "'"+jComboBox3.getSelectedItem().toString()+"','"+jTextField2.getText()+
only 12 values so remove colmun and it ( but the correct ;-) ) and it should work
I solved the error because i was missing a comma between two columns.
private void insertActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
dbconnection db = new dbconnection();
try {
db.connect();
db.stm=db.con.createStatement();
java.sql.Date date1 = new java.sql.Date(jDateChooser1.getDate().getTime());
int result=db.stm.executeUpdate("insert into Blood_Test_Result" +"(DID,D_Name,Weight,HBsAG,HIV,VDRL,HCV,Malaria,Blood_Type,Blood_Status,LTID,LT_Name,Date)"
+"values('"+jComboBox2.getSelectedItem().toString()+"',"
+ "'"+jTextField1.getText()+"','"+jTextField3.getText()+"','"+jComboBox4.getSelectedItem().toString()+"',"
+ "'"+jComboBox5.getSelectedItem().toString()+"','"+jComboBox6.getSelectedItem().toString()+"',"
+ "'"+jComboBox7.getSelectedItem().toString()+"','"+jComboBox8.getSelectedItem().toString()+"',"
+ "'"+jComboBox9.getSelectedItem().toString()+"','"+jComboBox10.getSelectedItem().toString()+"',"
+ "'"+jComboBox3.getSelectedItem().toString()+"','"+jTextField2.getText()+"','"+ date1 +"')");
JOptionPane.showMessageDialog(this, "insert successful");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
}
fill();
clear();
}
Thanks all for the help

SQL in Prepared Statement throwing SQL exception

I'm trying to figure out why this code is throwing an SQL exception. When I run this code it prints "Bad SQL in customer insert ps", which is the message in that inner catch block. I've got multiple prepared statements with SQL inserts like this both in this class and also elsewhere in my application. They're all working fine. I've looked through this one over and over again, and I can't figure out why this one is throwing an exception.
try {
Connection conn = DBconnection.getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT customerId FROM customer WHERE customerName=\"" + name + "\";");
System.out.println(ps.toString());
ResultSet rs = ps.executeQuery();
if (rs.next()) {
customerId = rs.getString("customerId");
}
try {
PreparedStatement customerInsert = DBconnection.getConnection().prepareStatement("INSERT "
+ "INTO customer (customerName, addressId, active, createDate, createdBy, lastUpdate, lastUpdateBy)"
+ "VALUES(\"" + name + "\", " + addressId + ", " + active + ", UTC_TIMESTAMP(), \"" + LogInController.getUserName() + "\", UTC_TIMESTAMP(), \"" + LogInController.getUserName() + "\");");
customerInsert.executeUpdate();
System.out.println(customerInsert.toString());
System.out.println(rs.toString());
} catch (SQLException sq) {
System.out.println("Bad SQL in customer insert ps");
}
} catch (SQLException customerIdException) {
System.out.println("Bad SQL in customer ps");
}
You're using PreparedStatement as though you were using Statement. Don't put the parameters in the SQL, put in placeholder ? marks. Then use the various setXyz methods (setString, setInt, etc.) to fill in the parameters:
PreparedStatement customerInsert = DBconnection.getConnection().prepareStatement(
"INSERT INTO customer (customerName, addressId, active, createDate, createdBy, lastUpdate, lastUpdateBy)" +
"VALUES(?, ?, ?, ?, ?, ?, ?);"
);
customerInsert.setString(1, name);
customerInsert.setInt(2, addressId);
// ...etc. Notice that the parameter indexes start with 1 rather than 0 as you might expect

How to optimize this update SQL query

I have this Java method which I will use to insert data from JSF form into Oracle:
public int saveData(int result) throws SQLException, java.text.ParseException, NoSuchAlgorithmException {
String SqlStatement = null;
if (ds == null) {
throw new SQLException();
}
Connection conn = ds.getConnection();
if (conn == null) {
throw new SQLException();
}
PreparedStatement ps = null;
/*
CREATE TABLE USERS(
USERID INTEGER NOT NULL,
GROUPID INTEGER,
SPECIALNUMBER VARCHAR2(60 ),
USERNAME VARCHAR2(50 ),
PASSWD VARCHAR2(50 ),
DATETOCHANGEPASSWD DATE,
ADDRESS VARCHAR2(60 ),
STATEREGION VARCHAR2(50 ),
COUNTRY VARCHAR2(50 ),
USERSTATUS VARCHAR2(30 ),
TELEPHONE VARCHAR2(50 ),
DATEUSERADDED DATE,
USEREXPIREDATE DATE,
DATEUSERLOCKED CHAR(20 ),
CITY VARCHAR2(50 ),
EMAIL VARCHAR2(50 ),
DESCRIPTION CLOB
)
/
*/
try {
conn.setAutoCommit(false);
boolean committed = false;
try { /* insert into Oracle the default system(Linux) time */
InsertSqlStatement = "INSERT INTO USERS"
+ " (USERID, GROUPID, SPECIALNUMBER, USERNAME, PASSWD, DATETOCHANGEPASSWD,"
+ " ADDRESS, STATEREGION, COUNTRY, USERSTATUS, TELEPHONE, DATEUSERADDED,"
+ " USEREXPIREDATE, DATEUSERLOCKED, CITY, EMAIL, DESCRIPTION)"
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
UpdateSqlStatement = "UPDATE USERS "
+ "SET "
+ "USERID = ?, "
+ "GROUPID = ?, "
+ "SPECIALNUMBER = ?, "
+ "USERNAME = ?, "
+ "PASSWD = ?, "
+ "DATETOCHANGEPASSWD = ?, "
+ "ADDRESS = ?, "
+ "STATEREGION = ?, "
+ "COUNTRY = ?, "
+ "USERSTATUS = ?, "
+ "TELEPHONE = ?, "
+ "DATEUSERADDED = ?, "
+ "USEREXPIREDATE = ?, "
+ "DATEUSERLOCKED = ?, "
+ "CITY = ?, "
+ "EMAIL = ?, "
+ "DESCRIPTION = ? "
+ "WHERE USERID = " + id;
ps = conn.prepareStatement(SqlStatement);
ps.setString(1, settingsMap.get("USERID"));
ps.setString(2, settingsMap.get("GROUPID"));
ps.setString(3, settingsMap.get("SPECIALNUMBER"));
ps.setString(4, settingsMap.get("USERNAME"));
ps.setString(5, passwdConvert(settingsMap.get("PASSWD")));
ps.setDate(6, toDate(settingsMap.get("DATETOCHANGEPASSWD")));
ps.setString(7, settingsMap.get("ADDRESS"));
ps.setString(8, settingsMap.get("STATEREGION"));
ps.setString(9, settingsMap.get("COUNTRY"));
ps.setString(10, settingsMap.get("USERSTATUS"));
ps.setString(11, settingsMap.get("TELEPHONE"));
ps.setDate(12, toDate(settingsMap.get("DATEUSERADDED")));
ps.setDate(13, toDate(settingsMap.get("USEREXPIREDATE")));
ps.setDate(14, toDate(settingsMap.get("DATEUSERLOCKED")));
ps.setString(15, settingsMap.get("CITY"));
ps.setString(16, settingsMap.get("EMAIL"));
ps.setString(17, settingsMap.get("DESCRIPTION"));
ps.executeUpdate();
conn.commit();
committed = true;
}
finally
{
if (!committed) {
conn.rollback();
}
}
} finally {
/* Release the resources */
ps.close();
conn.close();
}
return result;
}
Right now I cannot test the SQL query. Can you tell me is it valid and how I can optimize the SQL query for performance?
Right now I cannot test the SQL query. Can you tell me is it valid ...
Not with any certainty. (Why don't you wait until you CAN test it??)
... and how I can optimize the SQL query for performance?
It is not entirely clear what you are trying to do. However, here are some suggestions on performance:
You are creating and releasing a database connection for each SQL statement executed. That has to be bad for performance.
There is no need to do an insert followed by an update of the same record ... if that is what you are proposing to do.
You will get performance by doing a bulk or batch insert or update rather than inserting records one at a time.
If you are inserting lots of data into an empty table with lots of indexes, then you may get better performance if you do the insertions first and create the indexes afterwards.
At the level of a single query (i.e. the "UPDATE"), you probably cannot make the query significantly faster.
The only improvement you can make is put the id as '?' also:
UPDATE USERS "
+ "SET "
+ "USERID = ?, "
+ "GROUPID = ?, "
+ "SPECIALNUMBER = ?, "
+ "USERNAME = ?, "
+ "PASSWD = ?, "
+ "DATETOCHANGEPASSWD = ?, "
+ "ADDRESS = ?, "
+ "STATEREGION = ?, "
+ "COUNTRY = ?, "
+ "USERSTATUS = ?, "
+ "TELEPHONE = ?, "
+ "DATEUSERADDED = ?, "
+ "USEREXPIREDATE = ?, "
+ "DATEUSERLOCKED = ?, "
+ "CITY = ?, "
+ "EMAIL = ?, "
+ "DESCRIPTION = ? "
+ "WHERE USERID = ?";
And of course add a set decleration:
ps.setInt(18, id);
I think there is nothing to optimize because you are inserting to only one table. Same for update. There are no joins or grouping so there is really anything you can do about it. Maybe just one note - you could use StringBuilder for code formatting :-)
If you are going to insert several rows, then you could increase performance by reusing the database connection, as well as the prepared statement. The latter requires treating the user id as a row as well, the way ftom2 suggested. Apart from that, there is little room for performance optimizations.

Categories

Resources