Using a prepared statement with auto increment field - java

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);
//...

Related

problem in checking for email registration

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>");
}

java.sql.SQLException: Can not issue executeUpdate() or executeLargeUpdate() for SELECTs

I am trying register page, if email exits already it should get alert message, for this below is my some part of the code, i am using executeQuery for Select query but still i am getting error:
java.sql.SQLException: Can not issue executeUpdate() or executeLargeUpdate() for SELECTs
java code:
Class.forName("com.mysql.jdbc.Driver");
Connection cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/xxxx", "root","root");
PreparedStatement ps=cn.prepareStatement("select * from Register where email=?");
ps.setString(1, email);
ResultSet rs=ps.executeQuery();
if(rs.next())
{
out.println("<script type=\"text/javascript\">");
out.println("alert('Email already Exists Please Try with New Email');");
out.println("location='index.html';");
out.println("</script>");
}
else{
PreparedStatement ps1 = cn.prepareStatement("insert into Register values(?,?,?,?,?)");
ps1.setString(1, name);
ps1.setString(2, email);
ps1.setString(3, mobile);
ps1.setString(4, password);
ps1.setString(5, conform_password);
int i = ps.executeUpdate();
if (i != 0) {
response.sendRedirect("index.html");
} else {
out.println("Some Thing went wrong. Try Again...");
}
}
}
My guess is that the problem has to do with your not closing the first statement used for the select before you try to create another statement for the insert. But, there is a better way to implement your logic, using a single insert:
String sql = "INSERT INTO Register (name, email, mobile, password, confirm_password) ";
sql += "SELECT ?, ?, ?, ?, ? ";
sql += "WHERE NOT EXISTS (SELECT 1 FROM Register WHERE email = ?)";
PreparedStatement ps = cn.prepareStatement(sql);
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, mobile);
ps.setString(4, password);
ps.setString(5, conform_password);
ps.setString(6, email);
int i = ps.executeUpdate();
if (i == 0) {
System.out.println("Email already Exists Please Try with New Email");
}
else {
response.sendRedirect("index.html");
}
If the exists clause of the above insert fails, then nothing should be inserted, and the DML row count returned by executeUpdate() should be zero.

Java String insertion to MySQL field of type MEDIUMTEXT

I'm taking a string and inserting it into a mySQL database field of type MEDIUMTEXT. When I print it out, there is a bunch of '-' characters and whitespace surrounding a slightly corrupted version of my original text. Am I doing this wrong?
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/tripDB?characterEncoding=utf8","root","pass");
Statement stmt = con.createStatement();
query = "insert into trip (name, date, details) values (?, ?, ?)";
PreparedStatement preparedStmt = con.prepareStatement(query);
preparedStmt.setString(1, name); //Inserts correctly (varchar)
preparedStmt.setString(2, date); //Correct (varchar)
preparedStmt.setString(3, details); //Corrupted (MEDIUMTEXT)
preparedStmt.execute();
con.close();

Java JDBC Prepared Statement not inserting single quotes (SQL Escaping)

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&apos;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&apos;&apos;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 &apos;?
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
}

What am I doing wrong in inserting data to mysql table?

After executing code I get the Data saved message but no data is recorded in my clients table? I'm new to databases with Java, What am I doing wrong or how can I fix my code?
String sqlUrl = "jdbc:mysql://localhost:3306/clientinformation";
String user = "root";
String pass = "root";
String name = firstName.getText();
String lname = lastName.getText();
String cEmail = email.getText();
String rate = rateDbl.getText();
String cUrl = url.getText();
try {
Connection con = DriverManager.getConnection(sqlUrl, user, pass);
PreparedStatement st = con.prepareStatement("insert into clients
values('"+name+"', '"+lname+"', "
+ "'"+cEmail+"', '"+rate+"', '"+cUrl+"')");
JOptionPane.showMessageDialog(null, "Data saved!");
} catch (SQLException ex) {
Logger.getLogger(newClient.class.getName()).log(Level.SEVERE, null, ex);
}
What am I doing wrong
Well, you're building your SQL statement by concatenating values. That leads to SQL injection attacks - amongst other issues. Fortunately, that hasn't actually created a problem just yet - because you're never executing your statement.
You need to:
Parameterize your SQL, to avoid a SQL injection attack - use question marks for the parameters, and then use st.setString to set each parameter:
Connection con = DriverManager.getConnection(sqlUrl, user, pass);
PreparedStatement st = con.prepareStatement(
"insert into clients values (?, ?, ?, ?, ?)");
st.setString(1, name);
st.setString(2, lname);
st.setString(3, cEmail);
st.setString(4, rate); // Should this really be a string?
st.setString(5, cUrl);
st.executeUpdate();
JOptionPane.showMessageDialog(null, "Data saved!");
Call st.executeUpdate before you display the dialog box. (Ideally you shouldn't be mixing UI and data access in the same method, but...)
Please make the changes in that order though - do not just add a call to st.executeUpdate, or you've got a horrible security hole in your app.
The reason you're not seeing the data is you prepare the statement but never execute it. Call st.execute(); or st.executeUpdate(); to execute it.
Separately, though: That code is subject to SQL injection (attacks or otherwise); fun illustration here. Half the point of prepared statements is to protect against them. Use the parameters that prepared statements give you:
PreparedStatement st = con.prepareStatement("insert into clients values(?, ?, ?, ?, ?)");
int n = 1;
st.setString(n++, name);
st.setString(n++, lname);
st.setString(n++, cEmail);
st.setString(n++, rate);
st.setString(n++, cUrl);
// And then the missing execute
st.execute();

Categories