I never used this class PreparedStatementCreator and normally when I want to execute a query I do something like: INSERT INTO table (a,b,c...) values (?,?,?...), but in this case the MySQL query is: INSERT INTO table() values() ??
Can you explain me that? I can't understand how the columns are tracked...
The following code is the method. Thanks in advance:
public String add(String identificationNumber, String firstName, String lastName, String email, String cellphone,
String city, String gender, BloodType bloodType, ShirtSize shirtSize, String emergencyContactName,
String emergencyContactPhone, String eps, Long birthday, Integer isVolunteer, Group group) {
PreparedStatementCreator psc = new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
String sql = "INSERT INTO participants() VALUES()";
return con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
}
};
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(psc, keyHolder);
String id = keyHolder.getKey().toString();
modify(id, identificationNumber, firstName, lastName, email, cellphone, city, gender, bloodType, shirtSize,
emergencyContactName, emergencyContactPhone, eps, birthday, isVolunteer);
if (group != null && !Utilities.emptyString(group.getId()))
setGroup(id, group);
return id;
}
public void modify(String id, String identificationNumber, String firstName, String lastName, String email,
String cellphone, String city, String gender, BloodType bloodType, ShirtSize shirtSize,
String emergencyContactName, String emergencyContactPhone, String eps, Long birthday, Integer isVolunteer) {
Object[] args = new Object[] { identificationNumber, firstName, lastName, email, cellphone, city, gender,
bloodType == null ? null : bloodType.toString(), shirtSize == null ? null : shirtSize.toString(),
emergencyContactName, emergencyContactPhone, eps, birthday, isVolunteer, id };
String sql = "UPDATE participants SET identificationNumber = ?, firstName = ?, lastName = ?, email = ?, cellphone = ?, city = ?, gender = ?, bloodType = ?, shirtSize = ?, emergencyContactName = ?, emergencyContactPhone = ?, eps = ?, birthday = ?, isVolunteer=? WHERE id = ?";
jdbcTemplate.update(sql, args);
}
You need to change following SQL :
String sql = "INSERT INTO participants() VALUES()";
Add Field name into participants() and add ? into VALUES().
Then you need to set the each ? value by following statements,
ps.setString(1, "test");
for each ? you need to set the values.
I hope this will work for you.
I finally got the answer to this, is very simple:
Inserts a row empty in the table.
Then gets the id of that row.
Calls modify to INSERT (really UPDATE the row).
That's all.
Related
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)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am trying to add a string in MySQL from a textbox in Java. I have tried many ways from different websites but it is of no use.
I have been trying to add the string to my database and have wasted by whole day in that. My database name is icseCorner and my table name is users. Please help me with this.
Here is what I have done till now -
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String fname = jTextField1.getText();
String mname = (jTextField2.getText());
String lname = (jTextField3.getText());
String add = (jTextArea1.getText());
String sch = (jTextField4.getText());
String usr = (jTextField9.getText());
String psw = (new String(jPasswordField1.getPassword()));
String email = (jTextField10.getText());
String mob = (jTextField11.getText());
String dist = (jTextField12.getText());
String state = ((String) jComboBox1.getSelectedItem());
String gen = "";
if (jRadioButton1.isSelected())
gen = (jRadioButton1.getText());
else if (jRadioButton2.isSelected())
gen = (jRadioButton2.getText());
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(URL, USER, PASSWORD);
String sql = "INSERT INTO users (firstName, middleName, lastName, district, mobile, gender, statae, email, password, username, school, address) values (?,?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement myStmt = con.prepareStatement(sql);
myStmt.setString(1, fname);
myStmt.setString(2, mname);
myStmt.setString(3, lname);
myStmt.setString(4, add);
myStmt.setString(5, sch);
myStmt.setString(6, usr);
myStmt.setString(7, psw);
myStmt.setString(8, email);
myStmt.setString(9, mob);
myStmt.setString(10, dist);
myStmt.setString(11, state);
myStmt.setString(12, gen);
myStmt.executeUpdate();
JOptionPane.showMessageDialog(null, "Registered successfull!");
} catch (Exception e) {
}
}
Try to set your prepared statement strings in the same order as you list your table fields (i.e. firstName, middleName, lastName, district, mobile, gender, statae, email, password, username, school, address).
String sql = "INSERT INTO users (firstName, middleName, lastName, district, mobile, gender, statae, email, password, username, school, address) values (?,?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement myStmt = con.prepareStatement(sql);
myStmt.setString(1, fname);
myStmt.setString(2, mname);
myStmt.setString(3, lname);
myStmt.setString(4, dist);
myStmt.setString(5, mob);
myStmt.setString(6, gen);
myStmt.setString(7, state);
myStmt.setString(8, email);
myStmt.setString(9, psw);
myStmt.setString(10, usr);
myStmt.setString(11, sch);
myStmt.setString(12, add);
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 = ?.)
I have the following method to a person into the database which later is used to create a person object:
public static void addPerson(String personCode, String firstName, String lastName,
String phoneNo, String street, String city, String state,
String zip, String country) {
Connection conn = database.com.airamerica.interfaces.DatabaseConnect.getConnection();
PreparedStatement ps;
ResultSet rs;
String addAddressQuery = "INSERT INTO `Addresses` (`street`,`city`,`state`,`zip`,`country`) VALUES (?,?,?,?,?)";
String checkAddress = "SELECT `address_ID` FROM `Addresses` WHERE street = ? AND city = ? AND state = ? AND zip = ? AND country = ?";
String addPersonQuery = "INSERT INTO `Persons` (`personCode`,`firstName`,`lastName`,`address_ID`,`phoneNumber`) VALUES (?,?,?,(SELECT `address_ID` FROM `Addresses` WHERE street = ? AND city = ? AND state = ? AND zip = ? AND country = ?),?)";
try
{
ps = conn.prepareStatement(checkAddress);
ps.setString(1, street);
ps.setString(2, city);
ps.setString(3, state);
ps.setString(4, zip);
ps.setString(5, country);
rs = ps.executeQuery();
if(!(rs.next())){
ps = conn.prepareStatement(addAddressQuery);
ps.setString(1, street);
ps.setString(2, city);
ps.setString(3, state);
ps.setString(4, zip);
ps.setString(5, country);
ps.executeUpdate();
ps.close();
}
ps.close();
rs.close();
ps = conn.prepareStatement(addPersonQuery);
ps.setString(1, personCode);
ps.setString(2, firstName);
ps.setString(3, lastName);
ps.setString(4, street);
ps.setString(5, city);
ps.setString(6, state);
ps.setString(7, zip);
ps.setString(8, country);
ps.setString(9, phoneNo);
ps.executeUpdate();
ps.close();
conn.close();
}
catch (SQLException e)
{
System.out.println("SQLException: ");
e.printStackTrace();
throw new RuntimeException(e);
}
}
The problem is when we insert a name like Miles O'Brien it gets inserted as Miles O'Brien I tried to escape using a method to replace the single quote (apostrophe) with two of them ('') for escaping. That method just caused data to be inserted as Miles O''Brien. How do we go about fixing this? The problem is at ps.setString(3, lastName); How do we get the last name into the database without it going in as '?
just in case you need it the engine is InnoDB and we are using default UTF8 as the collation.
As you can see the last name is passed to the method as well.
GIGO
A step debugger and a well placed break point or the following will show you that this is not related to JDBC at all.
A step debugger is the much preferred way to inspect running code!
public static void addPerson(final String personCode, final String firstName, final String lastName,
final String phoneNo, final String street, final String city, final String state,
final String zip, final String country) {
System.out.println(String.format("Last Name = %s",lastName));
// the rest of your code
}
I have this piece of code which inserts records into the accounts table:
String accNumber = jTextField5.getText();
String accName = jTextField4.getText();
String accAddress1 = jTextField3.getText();
String accAddress2 = jTextField2.getText();
String accCity = jTextField6.getText();
String accCounty = jTextField7.getText();
String accPostCode = jTextField9.getText();
String accContact = jTextField8.getText();
String query = "Insert into accounts (AccNo, name, address, address2, address3, City, County, PostCode, contact) values (?, ?, ?, ?, ?, ?, ?, ?, ?)";
try{
connect.pst = connect.con.prepareStatement(query);
connect.pst.setString(1, accNumber);
connect.pst.setString(2, accName);
connect.pst.setString(3, accAddress1);
connect.pst.setString(4, accAddress2);
connect.pst.setString(5, null);
connect.pst.setString(6, accCity);
connect.pst.setString(7,accCounty);
connect.pst.setString(8, accPostCode);
connect.pst.setString(9, accContact);
connect.pst.execute();
JOptionPane.showMessageDialog(null, "Saved");
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
This works just fine and inserts records into the accounts table. Next I have this piece of code which is meant to update the orderstable table which contains 6 fields; Order Number, AccNo, Incvoice Number, Description, Amount, VAT. The Order Number field has been set to auto increment
The code:
String accNumber = jTextField29.getText();
String invNo = jTextField20.getText();
String description = jTextField21.getText();
String vat = jTextField22.getText();
String amount = jTextField23.getText();
String query = "Insert into orderstable (Order Number, AccNo, Invoice Number, Description, Amount, VAT) values (?, ?, ?, ?, ?, ?)";
try{
connect.pst = connect.con.prepareStatement(query);
connect.pst.setString(1, "3");
connect.pst.setString(2, accNumber);
connect.pst.setString(3, invNo);
connect.pst.setString(4, description);
connect.pst.setString(5, amount);
connect.pst.setString(6, vat);
connect.pst.execute();
JOptionPane.showMessageDialog(null, "Saved");
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
This code above returns a SQL syntax error. I am not sure why. What could the reason be for this SQL syntax error?
You can not have the column names with space and if you do so you need to have then in backticks
Insert into orderstable
(`Order Number`, AccNo, `Invoice Number`, Description, Amount, VAT)
Check here for more details http://dev.mysql.com/doc/refman/5.0/en/identifiers.html
The auto increment field order number should not be include in the attribute section.
Your query should look like this
String query = "Insert into orderstable (AccNo, Invoice Number, Description, Amount, VAT) values (?, ?, ?, ?, ?)";
order number column should not be include in field list, because it is auto increment