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.
Related
I have a function to update the user's information as follows:
public void updateAccount(String username, String name, String address, String aboutMe, String
id) {
String sql = "update Account set username = '?', \n"
+ " [Full_Name] = '?',\n"
+ " [Address] = '?',\n"
+ " [about_me] = '?'\n"
+ " where id = ?";
try {
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, name);
ps.setString(3, address);
ps.setString(4, aboutMe);
ps.setString(5, id);
ps.executeUpdate();
} catch (Exception ex) {
Logger.getLogger(AccountDao.class.getName()).log(Level.SEVERE, null, ex);
}
}
and this code is giving me an error like this:
Severe: com.microsoft.sqlserver.jdbc.SQLServerException: The index 2 is out of range.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:191)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setterGetParam(SQLServerPreparedStatement.java:933)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setValue(SQLServerPreparedStatement.java:948)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setString(SQLServerPreparedStatement.java:1578)
at dao.AccountDao.updateAccount(AccountDao.java:117)
at controller.UserProfileController.doPost(UserProfileController.java:91)
I don't understand why it gives me the error "The index 2 is out of range" and is there any
way to fix it?
Don't enclose ? parameter markers in quotes. These are typed by the appropriate setter:
String sql = "update Account set username = ?, \n"
+ " [Full_Name] = ?,\n"
+ " [Address] = ?,\n"
+ " [about_me] = ?\n"
+ " where id = ?";
public class DataBase {
public static void main(String[] args) {
try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/company", , )) {
Type[] types = { new GraphicCard(), new HardDrive(), new Keyboard(), new Memory(), new Monitor(), new Mouse(), new Processor() };
Product product = new Product(10, types);
Range rangeUnitPrice = new Range(10_000, 220_000);
Range rangeQuantity = new Range(0, 20);
Statement statement = connection.createStatement();
while (product.getNumberOfEntery() > 0) {
String typeAndCatagory = product.getRandomType();
String name = product.getName(typeAndCatagory);
String description = product.getDescription();
double unit_Price = product.randomUnit_PriceGenerator(name, 'x', rangeUnitPrice);
int quantity_In_Stock = product.generateQuantity_In_Stock(rangeQuantity);
String brand = product.getRandomBrand();
System.out.println("Name: " + name + ", " + "Type: " + typeAndCatagory + ", " + "Random price: " + unit_Price + ", " + "Quantity in stock: " + quantity_In_Stock + ", " + "Random brand: " + brand);
String query = "INSERT INTO product VALUES (" + name + ", " + description + ", " + unit_Price + ", " + quantity_In_Stock + ", " + brand + ", " + typeAndCatagory + ", " + typeAndCatagory + ")";
statement.executeUpdate(query);
product.decreasesNumberOfEntrees();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
The query doesn't work, and the first value is the default (PRIMARY KEY AUTO-INCREMENT), which I don't need to specify. The error is below
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 '10 AMD graphic card Gamer Edition, ,
180657.63138583858, 6, HP, Graphic Card, Gr' at line 1
You format a string in this line to use as an SQL statement:
String query = "INSERT INTO product VALUES (" + name + ", " + description + ", " + unit_Price + ", " + quantity_In_Stock + ", " + brand + ", " + typeAndCatagory + ", " + typeAndCatagory + ")";
Something is wrong with this statement that makes it produce a syntax error. What is wrong?
It's difficult to debug this by staring at the Java expression. It's confusing to look at all the " and + and see what's wrong.
It would be easier to see what's wrong if you can see the final result of the string, not the Java expression that builds a string.
So before you execute it, try printing it out:
System.out.println(query);
Then the problem may be more clearly visible.
I predict it will look something like this:
INSERT INTO product VALUES (10 AMD graphic card Gamer Edition, , 180657.63138583858, 6, HP, Graphic Card, Gr...
This is missing quotes around the string values in your VALUES clause. It's not valid SQL.
The best solution is to learn to use query parameters. Then you don't have to worry about quotes around values. And the code is more secure from SQL injection.
In your case, something like the following:
String query = "INSERT INTO product VALUES (?, ?, ?, ?, ?, ?, ?)";
Statement statement = connection.prepareStatement(query);
while (product.getNumberOfEntery() > 0) {
// set the values for all your variables...
statement.setString(1, name);
statement.setString(2, description);
statement.setDouble(3, unit_Price);
statement.setInt(4, quantity_In_Stock);
statement.setString(5, brand);
statement.setString(6, typeAndCatagory);
statement.setString(7, typeAndCatagory);
statement.executeUpdate();
}
There are two problems with your code:
The major one is, your code is vulnerable to SQL Injection.
You will have to enclose the text values withing single quotes yourself.
The solution to both the problem is using PreparedStatement as shown below:
String query = "INSERT INTO product VALUES (?, ?, ?, ?, ?)";
try (PreparedStatement pstmt = con.prepareStatement(query)) {
//...
pstmt.setString(1, name);
pstmt.setString(2, description);
pstmt.setDouble(3, unit_Price);
//...
pstmt.executeUpdate();
}
Also, I suggest you always follow Java naming conventions e.g. unit_Price should be named as unitPrice.
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();
}
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);
}
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 (' ....