I have an error when I try to update the record in MSSQL.
My code:
PreparedStatement ps = con.prepareStatement("UPDATE tblUsers SET firstName='?', lastName = '?', phone = ?,"
+ "[group] = ?, picture = ?, address = ? Where id=?");
ps.setString(1, firstName);
ps.setString(2, lastName);
//update phone has two conditions
if (!phone.isEmpty()) {
ps.setString(3, "'" + phone + "'");
} else {
ps.setString(3, null);
}
ps.setInt(4, group);
//update img has two conditions
if (pathImg != null) {
ps.setBytes(5, MyUtils.getImgbinary(pathImg));
} else {
ps.setBytes(5, MyUtils.getImgbinary(defaultPathImg));
}
//update address has two conditions
if (!address.isEmpty()) {
ps.setNString(6, "'" + address +"'");
} else {
ps.setNString(6, null);
}
ps.setInt(7, userID);
When I tried to executeUpdate(), 'The index 6 is out of range' error throws. I don't understand why?
In here, address can be null.
Related
I want to insert two different rows on two other tables. How can I do that? I have read about batch execution but do not understand it clearly. If it is possible to use batch execution, how?
I have tried this way and got this message "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?, ?, ?, ?, ?, ?)' at line 1
". Thanks in advance.
/**
* save data from multiple tables
*/
private void customSave() {
// create connection
conn = new DB_Connection().makeConn();
try {
// for invoice table
String product_name = comboProductName.getSelectedItem().toString();
String date_of_sale = textDateOfSale.getText();
String paid_on = textPaidOn.getText();
int quantity = Integer.valueOf(spinnerQuantity.getValue().toString());
int discount = Integer.valueOf(textDiscount.getText());
double total_price = Double.valueOf(lblTotal.getText());
// for customer details table
String name = textFullName.getText();
String email = textEmail.getText();
String mobile = textMobile.getText();
String address = textAddress.getText();
stmnt = conn.createStatement();
// save to invoice
String sql_invoice = "INSERT INTO `invoice`(`product_name`, `date_of_sale`, `paid_on`, `discount`, `total_price`, `quantity`) "
+ "VALUES (?, ?, ?, ?, ?, ?)";
ps = conn.prepareStatement(sql_invoice);
ps.setString(1, product_name);
ps.setString(2, date_of_sale);
ps.setString(3, paid_on);
ps.setInt(4, discount);
ps.setDouble(5, total_price);
ps.setInt(6, quantity);
// save to customer_details
String sql_customer = "insert into customer_details(customer_name, email, mobile, address )"
+ "values (?, ?, ?, ?)";
ps = conn.prepareStatement(sql_customer);
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, mobile);
ps.setString(4, address);
if ((!textDateOfSale.getText().equals("")) && (!textPaidOn.getText().equals(""))
&& (!textFullName.getText().equals(""))) {
int count = ps.executeUpdate(sql_invoice);
int count1 = ps.executeUpdate(sql_customer);
if (count > 0 && count1 > 0) {
JOptionPane.showMessageDialog(null, "Data saved successfully.", "Success!!!",
JOptionPane.INFORMATION_MESSAGE);
textDateOfSale.setText("");
textPaidOn.setText("");
textFullName.setText("");
textEmail.setText("");
textMobile.setText("");
textAddress.setText("");
} else {
JOptionPane.showMessageDialog(null, "Unable to save data.", "Warning!!!",
JOptionPane.WARNING_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null, "Please fillup the required fields.", "Warning!",
JOptionPane.WARNING_MESSAGE);
}
stmnt.close();
conn.close();
} catch (Exception ex) {
// JOptionPane.showMessageDialog(null, ex, "Error!", JOptionPane.ERROR_MESSAGE);
System.out.println(ex.getMessage());
ex.getStackTrace();
}
}
I'd like to insert ID(int), title(varchar), plot(varchar), release_date(date), target(varchar) into exsiting database.
Here is the code which showed no data at all.
How can I add a date type value into a connected database?
else if (e.getSource() == this.insert2) {
String n = this.IDField.getInt();
String m = this.titleField.getText();
String f = this.plotField.getText();
String p = this.release_dateField.getText();
String t = this.targetField.getText();
String[] name = {"MOVIE_ID","title","plot","release_date","main_target"};
this.dt = new DefaultTableModel(name, 0);
/**try~catch*/
try{
stmt.executeUpdate("insert into DB2020_MOVIEINFO values('" + n + "', '" + m + "', '" + f + "', '" + p + "', '" + t + "')");
ResultSet rset_mv = stmt.executeQuery("SELECT * FROM DB2020_MOVIEINFO");
while (rset_mv.next()) {
Object[] data = {rset_mv.getString(1), rset_mv.getString(2), rset_mv.getString(3), rset_mv.getString(4), rset_mv.getString(5)};
dt.addRow(data);
}
}
catch(SQLException se) {
se.printStackTrace();
}
this.jt = new JTable(dt);
jt.getTableHeader().setBackground(Color.decode("#b76e79"));
jt.setSelectionBackground(Color.decode("#f7f6f0"));
this.jsp = new JScrollPane(jt);
jt.setPreferredScrollableViewportSize(new Dimension(800,600));
this.add(centerPanel,BorderLayout.CENTER);
this.centerPanel.removeAll();
this.centerPanel.updateUI();
this.centerPanel.add(jsp);
this.centerPanel.setVisible(true);
}
new code I applied after Mureinik's advise. (I extracted date-part)
else if (e.getSource() == this.insert2) {
Int id = this.IDField.getInt();
String title = this.titleField.getText();
String plot = this.plotField.getText();
String target = this.targetField.getText();
String[] name = {"MOVIE_ID","title","plot","main_target"};
this.dt = new DefaultTableModel(name, 0);
/**try~catch*/
try (PreparedStatement ps =
conn.prepareStatement("insert into DB2020_MOVIEINFO values(?, ?, ?, ?)") {
ps.setInt(1, id); // id should be an int
ps.setString(2, title);
ps.setString(3, plot);
ps.setString(4, target);
}
catch(SQLException se) {
se.printStackTrace();
}
this.jt = new JTable(dt);
jt.getTableHeader().setBackground(Color.decode("#b76e79"));
jt.setSelectionBackground(Color.decode("#f7f6f0"));
this.jsp = new JScrollPane(jt);
jt.setPreferredScrollableViewportSize(new Dimension(800,600));
this.add(centerPanel,BorderLayout.CENTER);
this.centerPanel.removeAll();
this.centerPanel.updateUI();
this.centerPanel.add(jsp);
this.centerPanel.setVisible(true);
}
Instead of trying to force these datatypes to strings, you could use a PreparedStatement and let the JDBC driver do the heavy lifting for you. As a side effect, this will also help protect you application from SQL Injection attacks:
try (PreparedStatement ps =
conn.prepareStatement("insert into DB2020_MOVIEINFO values(?, ?, ?, ?, ?)) {
ps.setInt(1, id); // id should be an int
ps.setString(2, title);
ps.setString(3, plot);
ps.setDate(4, releaseDate); // releaseDate should be java.sql.Date
ps.setString(5, target);
}
The update button on my simple stock management system is not updating the stock. When clicked it shows the product updated dialog but nothing happens. It is throwing no errors and i cant find the problem.
It was working when i only had 5 rows but when i added the category and quantity row it stopped.
private void btn_updateActionPerformed(java.awt.event.ActionEvent evt) {
if(checkInputs() && txt_id.getText() != null)
{
String UpdateQuery = null;
PreparedStatement ps = null;
Connection con = getConnection();
//update without image
if(ImgPath == null)
{
try {
UpdateQuery = "UPDATE products SET name = ?, price = ?"
+ ", add_date = ?, category = ?, quantity = ?, WHERE id = ?";
ps = con.prepareStatement(UpdateQuery);
ps.setString(1, txt_name.getText());
ps.setString(2, txt_price.getText());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String addDate = dateFormat.format(txt_AddDate.getDate());
ps.setString(3, addDate);
ps.setInt(4, Integer.parseInt(txt_id.getText()));
String value = combo_category.getSelectedItem().toString();
ps.setString(5, value);
ps.setString(6, txt_quantity.getText());
ps.executeUpdate();
Show_Products_In_JTable();
JOptionPane.showMessageDialog(null, "Product Updated");
} catch (SQLException ex) {
Logger.getLogger(Main_Window.class.getName()).log(Level.SEVERE, null, ex);
}
}
//update with Image
else{
try{
InputStream img = new FileInputStream(new File(ImgPath));
UpdateQuery = "UPDATE products SET name = ?, price = ?"
+ ", add_date = ?,image = ?, category = ?, quantity = ?, WHERE id = ?";
ps = con.prepareStatement(UpdateQuery);
ps.setString(1, txt_name.getText());
ps.setString(2, txt_price.getText());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String addDate = dateFormat.format(txt_AddDate.getDate());
ps.setString(3, addDate);
ps.setBlob(4, img);
String value = combo_category.getSelectedItem().toString();
ps.setString(5, value);
ps.setInt(6, Integer.parseInt(txt_id.getText()));
ps.executeUpdate();
Show_Products_In_JTable();
JOptionPane.showMessageDialog(null, "Product Updated");
}catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
}else{
JOptionPane.showMessageDialog(null, "One or More Fields Are Empty Or Wrong");
}
}
At first sight
quantity = ?, WHERE id = ?
shoule be
quantity = ? WHERE id = ?
I am using JDBC and mySQL to do an application for a family. After logging in into the system, the user can register for a family account. By SQL statement, I want to ensure that the input they keyed in is not repeated and they can only register when the database have a NRIC of them individually. I am working with JDBC and implementing the SQL statement in Java also. For now my problem is the system does not validate the input the user keys in and let's the information to be passed to database easily. Would appreciate some help!
*NRIC = Identity Card No
Snapshots of Database:
User Database
Family Account Database
Code
public boolean regFamily(FamilyAccount myFam, Customer myCust) throws Exception {
int fid = 0;
try {
String selectStatement2 = "SELECT * from familyok.user where nric = ? and familyid is NOT NULL ";
PreparedStatement pStmt2 = con.prepareStatement(selectStatement2);
pStmt2.setString(1, myCust.getNric());
ResultSet rs2 = pStmt2.executeQuery();
if (rs2.next()) {
String insertStatement = "Insert into familyok.familyaccount (familyname, fnric1, fnric2, fnric3)";
insertStatement = insertStatement + "values (?,?,?,?)";
PreparedStatement prepStmt = con.prepareStatement(insertStatement);
prepStmt.setString(1, myFam.getFamilyname());
prepStmt.setString(2, myFam.getFnric1());
prepStmt.setString(3, myFam.getFnric2());
prepStmt.setString(4, myFam.getFnric3());
int status = prepStmt.executeUpdate();
if (status != 0) {
String selectStatement = "SELECT fid FROM familyok.familyaccount WHERE fnric1=?";
PreparedStatement pStmt = con.prepareStatement(selectStatement);
pStmt.setString(1, myFam.getFnric1());
ResultSet rs = pStmt.executeQuery();
if (rs.next()) {
System.out.println(rs.getInt("fid") + "\t");
fid = rs.getInt("fid");
String updateStatement = "update familyok.user set familyid=?, familyname1=? where nric in (?,?,?)";
PreparedStatement preparedStmt = con.prepareStatement(updateStatement);
preparedStmt.setInt(1, fid);
preparedStmt.setString(2, myFam.getFamilyname());
preparedStmt.setString(3, myFam.getFnric1());
preparedStmt.setString(4, myFam.getFnric2());
preparedStmt.setString(5, myFam.getFnric3());
int status2 = preparedStmt.executeUpdate();
System.out.println("update=" + preparedStmt.toString());
if (status2 != 0) {
System.out.println("Family Account Created");
return true;
}
}
}
}
else
{
System.out.println("Can't Register");
return false;
}
} catch (Exception ex) {
throw new Exception("Error: " + ex.getMessage());
}
return false;
}
On this java method I am trying to get data from a ms-sql server. I am trying to get the int value from a column , Now the columns I am using are all int's but for some reason when i try pulling it as a INT I am getting a number format error saying that the column is a nvarchar. Not sure what is happening and when i ran the System.out I am noticing I am only pulling the column name but no data that the column has. Here is my method, I am not sure what I am doing wrong or what is missing from this. Any help will be greatly appreciated thank you.
private boolean CheckEmployee(long bDays) throws ClassNotFoundException, SQLException {
PreparedStatement preparedStatement;
String type = getTypeOfTimeOff().replaceAll("\\s+","");
Connection conn = null;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(url, userName, password);
String selectProject = "SELECT ? FROM EmpVacationTbl Where FullName =? "
+ "AND ManagerName =?";
preparedStatement = conn.prepareStatement(selectProject);
preparedStatement.setString(1, getTypeOfTimeOff().replaceAll("\\s+",""));
preparedStatement.setString(2, getEmpName());
preparedStatement.setString(3, getManagerName());
System.out.println(preparedStatement.toString());
try (ResultSet rs = preparedStatement.executeQuery())
{
while (rs.next())
{
//int checker = rs.getInt(1);
String acheck = rs.getString(1);
System.out.println("TIME off the user has : " + acheck);
int checker = Integer.valueOf(acheck);
if(checker < bDays)
{
conn.close();
message = "Too many days";
return false;
}
else
{
conn.close();
return true;
}
}
if (rs.wasNull()) {
{
conn.close();
message = "Unable to find the days";
return false;
}
}
}
conn.close();
message = "Information not matching recordings.";
return false;
}
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
int aCheck = rs.getInt("column name");
}
}catch(){}
like this
For some reason what i did was add an AS to my query along with adding a if statement to my code caused the resultset to work with my code and allowed me to pull numbers from my database. Thank you for your help. Here is the updated code i added if it helps anyone.
private boolean CheckEmployee(long bDays) throws ClassNotFoundException, SQLException {
PreparedStatement preparedStatement;
Connection conn = null;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(url, userName, password);
String selectProject = null;
if(getTypeOfTimeOff().equalsIgnoreCase("Vacation Day"))
selectProject = "SELECT VacationDay As dayList FROM EmpVacationTbl Where FullName =? "
+ "AND ManagerName =?";
else if(getTypeOfTimeOff().equalsIgnoreCase("Bonus Day"))
selectProject = "SELECT BonusDay As dayList FROM EmpVacationTbl Where FullName =? "
+ "AND ManagerName =?";
else if(getTypeOfTimeOff().equalsIgnoreCase("Birthday Day"))
selectProject = "SELECT BirthdayDay As dayList FROM EmpVacationTbl Where FullName =? "
+ "AND ManagerName =?";
System.out.println("Query String : " + selectProject);
preparedStatement = conn.prepareStatement(selectProject);
preparedStatement.setString(1, getEmpName());
preparedStatement.setString(2, getManagerName());
System.out.println(preparedStatement.toString());
try (ResultSet rs = preparedStatement.executeQuery())
{
while (rs.next())
{
int checker = 0 ;
checker = rs.getInt("dayList");
System.out.println("Days the user has off are: " + checker );
if(checker < bDays)
{
conn.close();
message = "Too many days";
return false;
}
else
{
conn.close();
return true;
}
}
if (rs.wasNull()) {
{
conn.close();
message = "Unable to find the days";
return false;
}
}
}
conn.close();
message = "Information not matching recordings.";
return false;
}