I am having an issue with updating the Blob, the issue is that the pst.executeUpdate with not execute, however, if I take out the everything that relates the the Blob/Tryinng to update the Blob everything else will update i.e. ID, Name, Address etc. Everything functions as it should, the issue is just with the Blob.
updateEmployee.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Connection connection = null;
PreparedStatement pst = null;
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:employeeDatabase.sqlite");
connection.setAutoCommit(false);
int idVal = Integer.parseInt(idTextField.getText());
String nameVal= nameTextField.getText();
String genderVal = genderTextField.getText();
String dobVal = dobTextField.getText();
String addressVal = addressTextField.getText();
String postcodeVal = postcodeTextField.getText();
String ninVal = ninTextField.getText();
String jobVal = jobtitleTextField.getText();
String startDateVal = startdateTextField.getText();
String salaryVal = salaryTextField.getText();
String emailVal = emailTextField.getText();
//Icon photoBlob = photoLabel.getIcon();
InputStream img = new FileInputStream(s);
String sql = "UPDATE employees set ID= '"+ idVal+"', Name = '"+ nameVal +"', Gender ='"+ genderVal+"', DOB='"+ dobVal+"', Address ='"+ addressVal+"', Postcode ='"+ postcodeVal+"', NIN ='"+ ninVal+"', JobTitle='"+ jobVal+"', StartDate ='"+ startDateVal+"', Salary ='"+ salaryVal+"', Email='"+ emailVal+"', Images='"+ img+" WHERE ID= '"+ idVal+"'";
pst = connection.prepareStatement(sql);
pst.setInt(1,Integer.parseInt(idTextField.getText()));
pst.setString(2, nameTextField.getText());
pst.setString(3, genderTextField.getText());
pst.setString(4, dobTextField.getText());
pst.setString(5, addressTextField.getText());
pst.setString(6, postcodeTextField.getText());
pst.setString(7, ninTextField.getText());
pst.setString(9, startdateTextField.getText());
pst.setString(10, salaryTextField.getText());
pst.setString(11, emailTextField.getText());
pst.setBytes(12, readFile(s));
pst.executeUpdate();
System.out.println("Employee Updated");
JOptionPane.showMessageDialog(null, "Employee has successfully been updated");
connection.commit();
pst.close();
connection.close();
}
catch ( Exception e1 ) {
if(idTextField.getText().equals("")){
JOptionPane.showMessageDialog(null, "Please Ensure An Employee Has Been Selected");
}
}
}});
Edit -
I can however, insert and delete blob files as well as retrieve. Just this updating is giving me an issue.
Your SQL command text is not valid for a parameterized query. Instead of creating a dynamic SQL command string with imbedded values ...
String sql = "UPDATE employees set ID= '"+ idVal+"', Name = '"+ nameVal +"', Gender ='"+ genderVal+"', DOB='"+ dobVal+"', Address ='"+ addressVal+"', Postcode ='"+ postcodeVal+"', NIN ='"+ ninVal+"', JobTitle='"+ jobVal+"', StartDate ='"+ startDateVal+"', Salary ='"+ salaryVal+"', Email='"+ emailVal+"', Images='"+ img+" WHERE ID= '"+ idVal+"'";
... you should be using a command string with question marks as parameter placeholders ...
String sql = "UPDATE employees set ID = ?, Name = ?, Gender = ?, DOB = ?, Address = ?, Postcode = ?, NIN = ?, JobTitle = ?, StartDate = ?, Salary = ?, Email = ?, Images = ? WHERE ID = ?;
... and then using .setInt, .setString, .setBytes et al to set the parameter values.
(Note also that it is actually redundant to SET the "ID" value when you are using ... WHERE ID = ?.)
Related
In this example I want to check if eMail is registered or not. The function checkDuplicateEmail.emailCheck(emailcounter, email) will check the condition and return the boolean value. If the value is not true then it is supposed to insert the data but unfortunately it's not happening. Only in case eMail is matched the the else part is executing.
PreparedStatement st1 = conn.prepareStatement("SELECT * FROM customer where email = ?");
st1.setString(1,email);
ResultSet rs = st1.executeQuery();
checkDuplicateEmail checkDuplicateEmail = new checkDuplicateEmail();
while(rs.next()) {
emailcounter = rs.getString("email");
boolean isValid = checkDuplicateEmail.emailCheck(emailcounter, email);
}
if(!isValid) {
System.out.println("Email is Exists");
PreparedStatement st = conn.prepareStatement("insert into customer(name, email, mobileno, username, password) values(?, ?, ?, ?, ?)");
st.setString(1, name); //substituting ? with actual value
st.setString(2, email);
st.setInt(3, mobileNo);
st.setString(4, username);
String encoded = enc.encodeToString(password.getBytes());
st.setString(5, encoded);
st.executeUpdate();
conn.close();
}
else {
System.out.println("Email is already Exists");
PrintWriter out = response.getWriter();
out.write("<html><body>");
out.write("<h1>Registration cannot be sucessful because email is already registered!</h1>");
out.write("</body></html>");
}
I am trying to insert Appointment of the Doctor while selecting name of the Doctor it will insert ID only in the table database and updating Doctor Availability to 0
here is my code
try{
String sql = "INSERT INTO Appointment_Table (Doc_ID, Department_ID, SchedDate, Patient_ID) VALUES\n" +
"( (SELECT ID from User_Table where First_Name = ?), (SELECT Department_ID from User_Table WHERE First_Name = ?), ?, (Select Patient_ID from Patient_Records where First_Name = ?));";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
pst.setString(1, (String) DoctorNames.getSelectedItem());
pst.setString(2, (String) DoctorNames.getSelectedItem());
String add1 = ((JTextField)jDateChooser1.getDateEditor().getUiComponent()).getText();
String add2 = DoctorTime.getText();
pst.setString(3, add1+"-/-"+add2+"-PM");
pst.setString(4, (String) DoctorPatient.getSelectedItem());
try{
String sql1 = "Update User_Table set Availability = 0 where First_Name LIKE ?";
pst = pst = conn.prepareStatement(sql1);
rs = pst.executeQuery();
pst.setString(1, (String) DoctorNames.getSelectedItem());
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}finally {
try {
rs.close();
pst.close();
}catch(Exception e){
}
}
try to add LIMIT 0,1 after SELECT just like this:
INSERT INTO Appointment_Table (Doc_ID, Department_ID, SchedDate, Patient_ID) VALUES
( (SELECT ID from User_Table where First_Name = ? LIMIT 0,1 ), (SELECT Department_ID from User_Table WHERE First_Name = ? LIMIT 0,1 ), ?, (Select Patient_ID from Patient_Records where First_Name = ? LIMIT 0,1 ));
it is for MySql DBMS for SQL Server use Top 1 keyword
SELECT TOP 1 ID from User_Table where First_Name = ?
add 3 combo box to your form one for Doc_ID and one for Department_ID and another one for Patient_ID
make this class
class ComboItem
{
private String key;
private String value;
public ComboItem(String key, String value)
{
this.key = key;
this.value = value;
}
#Override
public String toString()
{
return key;
}
public String getKey()
{
return key;
}
public String getValue()
{
return value;
}
}
Add the ComboItem to your comboBox.
comboBox.addItem(new ComboItem("doctor name ", "Doc_ID"));
comboBox.addItem(new ComboItem("doctor 2 name ", "Doc_ID 2"));
comboBox.addItem(new ComboItem("doctor 3 name ", "Doc_ID 3"));
Whenever you get the selected item.
Object item = comboBox.getSelectedItem();
String value = ((ComboItem)item).getValue();
the edit your SQL
INSERT INTO Appointment_Table (Doc_ID, Department_ID, SchedDate, Patient_ID) VALUES (combo_Doc_ID_value,combo_Department_ID_value,?,combo_Patient_ID_value)
I have been trying to add values to a table named bill_items and this is the coding for the button "add to cart" but it shows and error saying "Unknown column Jacket in field list. What is wrong in this coding?
try {
rs = stmt.executeQuery("select * from mens_wear where Item_code = 1090;");
while(rs.next()){
icode = rs.getInt("Item_code");
p = rs.getInt("Price");
bname = rs.getString("Brand_Name");
iname = rs.getString("Item_Name");
t = rs.getString("Type");
}
rs.close();
stmt.close();
con.close();
} catch(Exception e)
{JOptionPane.showMessageDialog(null,e.getMessage());}
try {
Class.forName("java.sql.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/aashita","root","1510");
stmt = con.createStatement();
int a = stmt.executeUpdate("insert into bill_items values('"+icode+"','"+t+"','"+bname+"','"+iname+"','"+p+"');");
JOptionPane.showMessageDialog(null,"Added Successfully");
} catch(Exception e) {
JOptionPane.showMessageDialog(null,e.getMessage());
}
}
It is a bad practice to not specify column names in an insert and depend on table column order. There could also be an issue with escaping of your query string if any of your values contain quotes. I would try adding the column names and using a prepared statement with parameters.
string updateText = "insert into bill_items (Item_code, Type, Brand_Name, Item_Name, Price) ";
updateText += "values (?, ?, ?, ?, ?)";
PreparedStatement stmt = con.prepareStatement(updateText);
stmt.setInt(1, icode);
stmt.setString(2, t);
stmt.setString(3, bname);
stmt.setString(4, iname);
stmt.setInt(5, p);
int a = stmt.executeUpdate();
I have code like this
String sql_kode_kategori = "select kategori from data_kategori \n" +
"where kode_kategori = ?";
try{
pst = (PreparedStatement) koneksiMySQL.GetConnection().prepareStatement(sql_kode_kategori);
pst.setString(1, (String)cbKategori.getSelectedItem());
rst2 = pst.executeQuery();
rst2.next();
stat = (Statement) koneksiMySQL.GetConnection().createStatement();
String sql_insert = "INSERT INTO data_pasal VALUES ('"+jTPasal.getText() + "','"+jTIsi_Pasal.getText()+"'"
+ ",'"+jTHukuman.getText()+"','"+jTDenda.getText()+"','"+rst2.getString(1)+"')";
stat.executeUpdate(sql_insert);
javax.swing.JOptionPane.showMessageDialog(null, "Data CES Berhasil Ditambahkan");
ClearField();
TampilTabel();
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
i tried to get kode_kategori with kategori but that error appear, please help me
If rst2.next() returns false, there is no data for rst2.getString(1). You need to check for result as
if(rst2.next()) {
stat = (Statement) koneksiMySQL.GetConnection().createStatement();
String sql_insert = "INSERT INTO data_pasal VALUES ('"+jTPasal.getText() + "','"+jTIsi_Pasal.getText()+"'"
+ ",'"+jTHukuman.getText()+"','"+jTDenda.getText()+"','"+rst2.getString(1)+"')";
stat.executeUpdate(sql_insert);
} else {
// handle invalid category
}
Remove \n from your query:
String sql_kode_kategori = "select kategori from data_kategori where kode_kategori = ?";
Try to verify this (String)cbKategori.getSelectedItem() variable does contain right value.
Someone has suggested to use prepared statement but I don't know how to use it. What changes do I have to do in my code?
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("\n Driver loaded");
Connection con = DriverManager.getConnection("jdbc:odbc:wanisamajDB");
Statement stmt = con.createStatement();
System.out.println("statement is created");
// System.out.println(Integer.parseInt(cbregn.getSelectedItem().toString()));
String qry = " UPDATE Registration1 SET RegistrationNo = '"+cbregn.getSelectedItem()+"',SeniorPerson = '"+cbnm.getSelectedItem()+"', NativePlace = '"+tfplace.getText()+"',Kul = '"+tfkul.getText()+"', Gotra = '"+tfgotra.getText()+"' ,KulSwami = '"+tfswami.getText()+"', ResidensialAddress = '"+taraddr.getText()+"' , PinCode = '"+tfpcd.getText()+"', STDcode = '"+tfstdcode.getText()+"',TelephoneNo = '"+tftele.getText()+"', MobileNo = '"+tfmno.getText()+"', Email = '"+tfemail.getText()+"',Website ='"+tfweb.getText()+"',Education ='"+tfedu.getText()+"',Branch ='"+tfbrch.getText()+"',BloodGroup ='"+cbbldgrp.getSelectedItem()+"' where SeniorPerson='" +cbnm.getSelectedItem().toString()+"'" ;
stmt.executeUpdate(qry);
JOptionPane.showMessageDialog(null,"RECORD IS UPDATED SUCCESSFULLY ");
System.out.println("QUERY");
// cbregn.setEditable(false);
cbnm.setEditable(false);
tfplace.setEditable(false);
tfkul.setEditable(false);
tfgotra.setEditable(false);
tfswami.setEditable(false);
taraddr.setEditable(false);
tfpcd.setEditable(false);
tfstdcode.setEditable(false);
tftele.setEditable(false);
tfmno.setEditable(false);
tfemail.setEditable(false);
tfweb.setEditable(false);
tfedu.setEditable(false);
tfbrch.setEditable(false);
cbbldgrp.setEditable(false);
con.close();
stmt.close();
}
// catch(SQLException eM)
// {
// JOptionPane.showMessageDialog(null,"RECORD IS NOT FOUND ");
// }
catch(Exception et)
{
et.printStackTrace();
// System.out.println("error:"+et.getMessage());
}
see example
Prepared statements can help increase security by separating SQL logic from the data being supplied. This separation of logic and data can help prevent a very common type of vulnerability called an SQL injection attack. Normally when you are dealing with an ad hoc query, you need to be very careful when handling the data that you received from the user. This entails using functions that escape all of the necessary trouble characters, such as the single quote, double quote, and backslash characters. This is unnecessary when dealing with prepared statements. The separation of the data allows MySQL to automatically take into account these characters and they do not need to be escaped using any special function.
In your code instead of this:
String qry= " UPDATE Registration1 set RegistrationNo = '"+cbregn.getSelectedItem()+"',SeniorPerson = '"+cbnm.getSelectedItem()+"', NativePlace = '"+tfplace.getText()+"',Kul = '"+tfkul.getText()+"', Gotra = '"+tfgotra.getText()+"' ,KulSwami = '"+tfswami.getText()+"', ResidensialAddress = '"+taraddr.getText()+"' , PinCode = '"+tfpcd.getText()+"', STDcode = '"+tfstdcode.getText()+"',TelephoneNo = '"+tftele.getText()+"', MobileNo = '"+tfmno.getText()+"', Email = '"+tfemail.getText()+"',Website ='"+tfweb.getText()+"',Education ='"+tfedu.getText()+"',Branch ='"+tfbrch.getText()+"',BloodGroup ='"+cbbldgrp.getSelectedItem()+"' where SeniorPerson='" +cbnm.getSelectedItem().toString()+"'" ;
stmt.executeUpdate(qry);
try this:
String qry= " UPDATE Registration1 set RegistrationNo = ?,SeniorPerson = ?, NativePlace = ?,Kul = ?, Gotra = ?,KulSwami = ?, ResidensialAddress = ?, PinCode = ?, STDcode = ?,TelephoneNo = ?, MobileNo = ?, Email = ?,Website =?,Education =?,Branch =?,BloodGroup =? where SeniorPerson=?" ;
PreparedStatement updateQry = con.prepareStatement(qry);
updateQry.setString(1,cbregn.getSelectedItem());
updateQry.setString(2,cbnm.getSelectedItem());
updateQry.setString(3,tfplace.getText());
updateQry.setString(4,tfkul.getText());
updateQry.setString(5,tfgotra.getText());
updateQry.setString(6,tfswami.getText());
updateQry.setString(7,taraddr.getText());
updateQry.setString(8,tfpcd.getText());
updateQry.setString(9,tfstdcode.getText());
updateQry.setString(10,tftele.getText());
updateQry.setString(11,tfmno.getText());
updateQry.setString(12,tfemail.getText());
updateQry.setString(13,tfweb.getText());
updateQry.setString(14,tfedu.getText());
updateQry.setString(15,tfbrch.getText());
updateQry.setString(16,cbbldgrp.getSelectedItem());
updateQry.setString(17,cbnm.getSelectedItem().toString());
updateQry.executeUpdate():
public class UpdatesRecords{
public static void main(String[] args) {
System.out.println("Updates Records Example through Prepared Statement!");
Connection con = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/jdbctutorial","root","root");
try{
String sql = "UPDATE movies SET title = ? WHERE year_made = ?";
PreparedStatement prest = con.prepareStatement(sql);
prest.setString(1,"Sanam We wafafa");
prest.setInt(2,2005);
prest.executeUpdate();
System.out.println("Updating Successfully!");
con.close();
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
please use above code as reference and change your code