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
}
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>");
}
When I click on the Create button to add a supplier record in to my database, I receive the above error message.
Can someone help me where did I went wrong: is there something wrong with the insert statement.
private void jbtnCreateActionPerformed(java.awt.event.ActionEvent evt) {
try {
String sql = "INSERT INTO supplier"
+"(Full Name, Address Line 1, Address Line 2, Post Code, Email Address, Phone Number)"
+"VALUES (?,?,?,?,?,?)";
connection = DriverManager.getConnection("jdbc:mysql://localhost/inventory management", "root", "");
ps = connection.prepareStatement(sql);
ps.setString(1, txtname.getText());
ps.setString(2, txtaddressline1.getText());
ps.setString(3, txtaddressline2.getText());
ps.setString(4, txtpostcode.getText());
ps.setString(5, txtemail.getText());
ps.setString(6, txtphone.getText());
ps.executeUpdate();
JOptionPane.showMessageDialog(null, "Supplier Added");
} catch(SQLException | HeadlessException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
You have whitespaces in the column names (as well as in the connection string) which is not allowed. If you really need to use column names with spaces, put them in backticks:
String sql = "INSERT INTO supplier"
+"(`Full Name`, `Address Line 1`, `Address Line 2`, `Post Code`, `Email Address`, `Phone Number`)"
+"VALUES (?,?,?,?,?,?)";
However, it would be better to use snake case for the column names: full_name, etc.
I am having trouble trying to add dates to my database
This is my code
public void AddStudent(String idStudent, String name, String idClass, String dateOfBirth, String sex, String address){
Connection connect = classConnection.connect;
PreparedStatement ps = null;
String query = "insert into students values(?,?,?,?,?,?)";
try {
ps = connect.prepareStatement(query);
ps.setString(1, idStudent);
ps.setString(2, name);
ps.setString(3, sex);
ps.setString(4, dateOfBirth);
ps.setString(5, address);
ps.setString(6, idClass);
ps.execute();
} catch (SQLException e) {
JOptionPane.showMessageDialog(this, "Error: " + e.toString());
}
}
This is an error
conversion failed when converting date and/or time from character string
I have to solve it like, thanks
You need to parse it fist to date, on the same format as your database format().
For shortcut, you can use setDate from PreparedStatement;
hope this helps
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 trying to do insert to a table whose primary key is set to auto increment using a prepared statement.
The fields in the table are as follows;
id, username, password, email, firstname, last name
My code is such that
String sql = "INSERT INTO Users values (?,?,?,?,?, ?)";
RegistrationStatus status = null;
Connection conn = null;
PreparedStatement st = null;
try {
conn = source.getConnection();
st = conn.prepareStatement(sql);
st.setString(2, username);
st.setString(3, password);
st.setString(4, email);
st.setString(5, firstname);
st.setString(6, lastname);
st.executeUpdate();
Where i have read that we should no include the first item as the database will take care of it. This approach for me appears to be failing.
Would it be possible to get some help on how to solve this?
Change your statement to not include the id (or the exact name) column:
String sql = "INSERT INTO Users (username, password, email, firstname, lastname)"
+ " values (?,?,?,?,?)";
//...
st.setString(1, username);
st.setString(2, password);
st.setString(3, email);
st.setString(4, firstname);
st.setString(5, lastname);
//...