Why does setting explicit 'null' values fail for JDBC Update operation? - java

I am trying to update some attributes with null values. But it always error. Here is my code
// deleting records of column overtime, medical, bonus, other and totalamount
try {
String deleteQuery = "update paydb.allowance set "
+ "overtime = ?, "
+ "medical = ?,"
+ "bonus = ?,"
+ "other = ?,"
+ "totalamount = ?"
+ "where emp_id = ?";
PreparedStatement dpst = conn.prepareStatement(deleteQuery);
dpst.setNull(1, java.sql.Types.DOUBLE);
dpst.setNull(2, java.sql.Types.DOUBLE);
dpst.setNull(3, java.sql.Types.DOUBLE);
dpst.setNull(4, java.sql.Types.DOUBLE);
dpst.setNull(5, java.sql.Types.DOUBLE);
dpst.setString(6, txt_search.getText());
dpst.executeUpdate();
JOptionPane.showMessageDialog(null, "Record deleted successfully");
}
catch (SQLException e)
{
JOptionPane.showMessageDialog(null, e);
}

try {
String deleteQuery = "update paydb.allowance set "
+ "overtime = ?,"
+ "medical = ?,"
+ "bonus = ?,"
+ "other = ?, "
+ "totalamount = ? "
+ "where emp_id = ? ";
enter code here
PreparedStatement dpst = conn.prepareStatement(deleteQuery);
dpst.setNull(1, java.sql.Types.DOUBLE);
dpst.setNull(2, java.sql.Types.DOUBLE);
dpst.setNull(3, java.sql.Types.DOUBLE);
dpst.setNull(4, java.sql.Types.DOUBLE);
dpst.setNull(5, java.sql.Types.DOUBLE);
dpst.setString(6, txt_search.getText());
dpst.executeUpdate();
JOptionPane.showMessageDialog(null, "Record deleted successfully");
}
catch (SQLException e)
{
JOptionPane.showMessageDialog(null, e);
}

Related

jdbc application update sql isnt working for me, any ideas

public void Update(String name, String mobile, String email, String car, String model, String year, String color, String plate_no, String plateletters,String gear, String km, String date,String licesnse,String status, String notes){
Connection conn = null;
try{
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("connected");
Statement stmt = (Statement) conn.createStatement();
String ins = "update car"
+ "set Name = '"+name+"' , "
+ "Email = '"+email+"' , "
+ "Car = '"+car+"' , "
+ "Model = '"+model+"' , "
+ "Year = '"+year+"' , "
+ "Color = '"+color+"' , "
+ "Plateno = '"+plate_no+"' , "
+ "Plateletters = '"+plateletters+"' , "
+ "Gearbox = '"+gear+"' , "
+ "Km = '"+km+"' , "
+ "Date = '"+date+"' , "
+ "License = '"+licesnse+"' , "
+ "Status = '"+status+"' , "
+ "Notes = '"+notes+"' "
+ "where Mobile = '"+mobile+"' ";
stmt.execute(ins);
}catch(SQLException e){
JOptionPane.showMessageDialog(null, e.getMessage());
System.err.println(e);
return;
}
}
**i have tried prepared statment and stmt.executeUpdate(ins); but nothing workes !!
Please help!**
the 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 '= 'ahmed' , Email = 'ahmed#hotmail.com' , Car = 'honda' , Model = 'hondaz' , Yea' at line 1
You need to make sure you add proper space between elements in your SQL query:
String ins = "update car"
should be
String ins = "update car "
A good approach to doing this is to write and execute your SQL in your database query tool (SQL developer, phpMyAdmin, whatever) and make sure your syntax is good before trying to re-write it in Java.
Use a preparedStatement instaed of a Statement.
Connection conn = null;
try{
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
PreparedStatement pstm = conn.prepareStatement(
"update car "
+ "set Name = ? ,"
+ "Email = ? ,"
+ "Car = ? ,"
+ "Model = ? ,"
+ "Year = ? ,"
+ "Color = ? ,"
+ "Plateno = ? ,"
+ "Plateletters = ? ,"
+ "Gearbox = ? ,"
+ "Km = ?,"
+ "Date = ?,"
+ "License = ?, "
+ "Status = ?, "
+ "Notes = ? "
+ "where mobile = ?"
);
pstm.setObject(1, name);
pstm.setObject(2, email);
pstm.setObject(3, car);
pstm.setObject(4, model);
pstm.setObject(5, year);
pstm.setObject(6, color);
pstm.setObject(7, plate_no);
pstm.setObject(8, plateletters);
pstm.setObject(9, gear);
pstm.setObject(10, km);
pstm.setObject(11, date);
pstm.setObject(12, licesnse);
pstm.setObject(13, status);
pstm.setObject(14, notes);
pstm.setObject(15, mobile);
pstm.executeUpdate();
}catch(SQLException e){
e.printStackTrace();
}

Error My SQL in Java Language (Netbeans)

I have code:
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
con = Connect.ConnectDB();
if (PatientID.getText().equals("")) {
JOptionPane.showMessageDialog(this, "Please retrieve Patient ID", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (txtNoOfDays.getText().equals("")) {
JOptionPane.showMessageDialog(this, "Please enter no. of days", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (txtServiceCharges.getText().equals("")) {
JOptionPane.showMessageDialog(this, "Please retrieve service charges", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (txtBillingDate.getText().equals("")) {
JOptionPane.showMessageDialog(this, "Please enter billing date", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (txtTotalPaid.getText().equals("")) {
JOptionPane.showMessageDialog(this, "Please enter total paid", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
double add1 = Double.parseDouble(txtRoomCharges.getText());
double add = Double.parseDouble(txtNoOfDays.getText());
double add2 = add * add1;
txtTotalRoomCharges.setText(String.valueOf(add2));
double add3 = Double.parseDouble(txtServiceCharges.getText());
double add5 = ((add * add1) + add3);
txtTotalCharges.setText(String.valueOf(add5));
double paid = Double.parseDouble(txtTotalPaid.getText());
txtTotalPaid.setText(String.valueOf(paid));
if (add5 > paid) {
double datadue = add5 - paid;
txtDueCharges.setText(String.valueOf(datadue));
}
//double add1 = Double.parseDouble(txtTotalCharges.getText());
//double add2 = Double.parseDouble(txtTotalPaid.getText());
Statement stmt;
stmt = con.createStatement();
String sql1 = "Select DischargeID from bill_room where DischargeID= " + txtDischargeID.getText() + "";
rs = stmt.executeQuery(sql1);
if (rs.next()) {
JOptionPane.showMessageDialog(this, "Record already exists", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
String sql = "insert into bill_room(DischargeID,BillingDate,RoomCharges,ServiceCharges,PaymentMode,PaymentModeDetails,ChargesPaid,DueCharges,TotalCharges,NoOfDays,TotalRoomCharges) values(" + txtDischargeID.getText() + ",'" + txtBillingDate.getText() + "'," + txtRoomCharges.getText() + "," + txtServiceCharges.getText() + ",'" + cmbPaymentMode.getSelectedItem() + "','" + txtPaymentModeDetails.getText() + "'," + txtTotalPaid.getText() + "," + txtDueCharges.getText() + "," + txtTotalCharges.getText() + "," + txtNoOfDays.getText() + "," + txtTotalRoomCharges.getText() + ")";
pst = con.prepareStatement(sql);
pst.execute();
JOptionPane.showMessageDialog(this, "Successfully saved", "Record", JOptionPane.INFORMATION_MESSAGE);
btnSave.setEnabled(false);
} catch (HeadlessException | SQLException ex) {
JOptionPane.showMessageDialog(this, ex);
}
I have this code, when the execution runs (sometimes goes well, sometimes error.)
When error happen:
com.mysql.jdbc.exceptions.jbdc4.MySQLSyntaxErrorException" You have an
error in your SQL syntax; check the manual that corresponds to your
MariaDB server version for right sysntax to use near
'110800.0,9,10800.0); at line 1
When Run clearly
What is not quite right here?
I need your help or your suggest
You already use PreparedStatement why you don't use it properly, so to avoid syntax error and SQL injection you can use :
String sql = "insert into bill_room(DischargeID, BillingDate, "
+ "RoomCharges, ServiceCharges, PaymentMode, PaymentModeDetails, "
+ "ChargesPaid, DueCharges, TotalCharges, NoOfDays, TotalRoomCharges) "
+ "values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement insert = connection.prepareStatement(sql)) {
insert.setInt(1, txtDischargeID.getText());
insert.setString(2, txtBillingDate.getText());
//...Set the the right type if int use setInt if string use setString ...
insert.setDouble(11, Double.parseDouble(txtTotalRoomCharges.getText()));
insert.executeUpdate();
}
same thing with select.

sql Command has not properly ended

I'm using sql developer and netbeans when ever i try to insert data into the table this error "sql Command has not properly ended".
This is what i tried.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
dbconnection db = new dbconnection();
try {
db.connect();
db.stm = db.con.createStatement();
int result = db.stm.executeUpdate(
"insert into payment values'" + txt_paymentid.getText() + "','" + txt_reservation.getText() +"',
" + "'"+txt_fname.getText()+"',
'"+txt_lname.getText()+"' ,'"+txt_roomid.getText()+"' ,'"+txt_rate.getText()+"' ," + " '"+((JTextField)txt_datein.getDateEditor().getUiComponent()).getText()+"' ,"
+ "'"
((JTextField
)txt_dateout.getDateEditor().getUiComponent()).getText() + "'," + "'" + txt_days.getText() + "','" + txt_payment.getText() + "','" + txt_balance.getText() + "'"
);
if (result > 0) {
JOptionPane.showMessageDialog(this, "Data has been saved succesfully");
} else {
JOptionPane.showMessageDialog(this, "no data has been saved");
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(this, e.toString());
}
}
For a start
The sql should be in the ()
executeUpdate()("insert...
->
executeUpdate("insert...)
second it looks like the insert command itself it not valid
insert into table values (' ....

MySQLSyntaxErrorException: Unknown column ' ____ ' in 'field list'

I get the following MySQL exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'book.call_Number' in 'field list'.
What does that mean and how can I solve it?
Here is the code responsible for this exception:
public void actionPerformed(ActionEvent e) {
list.clearSelection();
String selectString = " ";
String afName = auth_fName.getText();
String aMI = auth_MI.getText();
String alName = auth_lName.getText();
String tField = titleField.getText();
String sField = subjectField.getText();
try {
Connection conn = Database.getConnection();
Statement s = conn.createStatement();
if (!afName.equals("") && (!aMI.equals("")) && (!alName.equals("")) && (!tField.equals("")) && (!sField.equals(""))) {
selectString = "SELECT a.call_Number as callNbr "
+ "FROM book a "
+ "FULL JOIN transaction b "
+ "ON a.call_Number=b.call_Number";
}
s = conn.createStatement();
System.out.println(selectString);
ResultSet rs = s.executeQuery(selectString);
while (rs.next()) {
String call_Num = rs.getString("call_Number");
String title = rs.getString("title");
String auth_lName = rs.getString("auth_lName");
String auth_MI = rs.getString ("auth_MI");
String auth_fName = rs.getString("auth_fName");
String availability = rs.getString("availability");
view = new View(call_Num, title, auth_lName, auth_MI, auth_fName, availability);
vList.add(view);
System.out.println(view);
}
rs.close();
s.close();
conn.close();
list.setListData(vList.toArray());
} catch (Exception ex) {
ex.printStackTrace();
}
}
Here is the DDL and content:
s.executeUpdate (
"CREATE TABLE book ("
+ "call_Number CHAR(10),"
+ "PRIMARY KEY (call_Number),"
+ "auth_fName CHAR(30)NOT NULL, auth_MI CHAR(2),"
+ "auth_lName CHAR(50)NOT NULL, title CHAR(100) NOT NULL,"
+ "subject CHAR(30) NOT NULL)");
count = s.executeUpdate (
"INSERT INTO book"
+ " VALUES"
+ "('MY.111.000', 'Mark', 'M','Bradshaw','Mystery Under the Sun','mystery'),"
+ "('MY.111.001', 'Mark','','Twain','The Adventures of Huckleberry Finn','mystery'),"
+ "('SF.111.002', 'Kito', 'M','Bradford','Mr. Roboto','science fiction'),"
+ "('SF.111.003', 'Eric','','Laslow','Science Fiction - Can It Happen?','science fiction'),"
+ "('AV.111.004', 'Rashad','','Cheeks','Fire Under the Bridge','adventure'),"
+ "('AV.111.005', 'Samantha','A','Appleby','The Open Sea','adventure'),"
+ "('CO.111.006', 'Lindsey', '','Butterby','What? We cant spend anymore!?','comedy'),"
+ "('CO.111.007', 'Judy', 'S','Yates','So this is life?','comedy'),"
+ "('IN.111.008', 'Elizabeth', 'J','Lee','Mystery Under the Sun','international'),"
+ "('IN.111.009', 'Gabriella', 'M','Rodriguez','Love in Brazil','international')");
*******t_action table***************************
//create transaction table
s.executeUpdate (
"CREATE TABLE t_action ("
+ "patron_ID CHAR(10) NOT NULL,"
+ "call_Number CHAR(10) NOT NULL, check_Out_Date DATE NOT NULL, check_In_Date DATE NOT NULL,"
+ "PRIMARY KEY (patron_ID, call_Number),"
+ "avail CHAR(15), total_Charge FLOAT)");
count3 = s.executeUpdate (
"INSERT INTO t_action"
+ " VALUES"
+ "('P222200000','MY.111.000','2011-03-08','2011-03-15','AVAILABLE',5.00),"
+ "('P222200001','MY.111.001','2011-03-31','2011-04-6','DUE 2011-04-6',5.00),"
+ "('P222200002','SF.111.002','2011-03-30','2011-04-5','DUE 2011-04-5',5.00),"
+ "('P222200003','SF.111.003','2011-03-29','2011-04-4','DUE 2011-04-4',5.00),"
+ "('P222200004','AV.111.004','2011-03-28','2011-04-3','DUE 2011-04-3',5.00),"
+ "('P222200005','AV.111.005','2011-03-27','2011-04-2','DUE 2011-04-2',5.00),"
+ "('P222200006','CO.111.006','2011-03-26','2011-04-1','DUE 2011-04-1',5.00),"
+ "('P222200007','CO.111.007','2011-01-06','2011-01-12','AVAILABLE',5.00),"
+ "('P222200008','IN.111.008','2011-02-06','2011-02-12','AVAILABLE',5.00),"
+ "('P222200009','IN.111.009','2011-03-06','2011-03-12','AVAILABLE',5.00)");
Use a <column> as predicate like below:-
selectString = "SELECT a.call_Number as callNbr, ... "
+ "FROM book a"
+ "FULL JOIN transaction b"
+ "ON a.call_Number=b.call_Number";
And then change the code to look for callNbr :-
String call_Num = rs.getString("callNbr");
HTH.
Change your query to this:
selectString = "SELECT a.call_Number "
+ "FROM book a "
+ "INNER JOIN transaction b "
+ "ON a.call_Number=b.call_Number";
MySQL does not support FULL OUTER JOIN. If you really need the effect of that - you'll need 2 selects with a UNION. Although from looks of it - does not seem like that would be necessary.

java-mysql program

i have a table - emp_details in mysql
i want to seatch an employ's id number in java.
if it is in the table , then show all the details of employee.
otherwise display an error message.
how i do this
Using JDBC
Here is an example You can build your solution from it.
Statement stmt = null;
String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from " + dbName + ".COFFEES";
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
int supplierID = rs.getInt("SUP_ID");
float price = rs.getFloat("PRICE");
int sales = rs.getInt("SALES");
int total = rs.getInt("TOTAL");
System.out.println(coffeeName + "\t" + supplierID + "\t" + price + "\t" + sales + "\t" + total);
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
} finally {
stmt.close();
}
ResultSet rs1=stmt.executeQuery("SELECT * FROM employee_details where Employee_ID='"+strEmpId+"'");
if(rs1.next()) {
System.out.println("Emp ID : " + rs1.getString(1));
System.out.println("Emp Name : " + rs1.getString(2));
System.out.println("Emp Salary : " + rs1.getString(3));
} else {
System.out.println("Emp ID not found");
}
If you want to know more about SQL just go through HERE

Categories

Resources