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);
Related
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
I have this method to check whether the email has already existed in my MySQL database. I am using the client-server model. This code here will says that the email existed no matter how I try entering new emails/fields.
public static String doAddUser(String firstName, String lastName, String email, String password, String retypedPassword) throws SQLException {
String returnStatement = "";
Connection connection = null;
connection = establishConnection();
final String queryCheck = "SELECT * from usersdata WHERE email = ?";
final PreparedStatement ps = connection.prepareStatement(queryCheck);
ps.setString(1, email);
final ResultSet resultSet = ps.executeQuery();
}
However, this code here will reset my connection immediately. I know that string concatenation in MySQL is a bad practice but nevertheless, this does not work.
public static String doAddUser(String firstName, String lastName, String email, String password, String retypedPassword) throws SQLException {
String returnStatement = "";
Connection connection = null;
connection = establishConnection();
final String queryCheck = "SELECT * from usersdata WHERE email = '" + email + "'";
final PreparedStatement ps = connection.prepareStatement(queryCheck);
ps.setString(1, email);
final ResultSet resultSet = ps.executeQuery();
}
Is there a way to work around this problem? I am stuck because I have 5 fields while I only need to validate the existence of one field only (email).
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 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);
//...
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Update a record if ID exist else Insert values
I am trying to update a value if the record exists else insert the values in the database. However, that is not working. I have written the code below :
NOTE: (Moderators, this is a repeated questions that I asked few mins ago. I am not able to edit previous one. Apologies if any inconvenience. Requesting you to delete.)
<%
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:sqlserver://10.222.10.19:1433", "sa", "admin1");
String empId = request.getParameter("empid");
String fName = request.getParameter("fName");
String lName = request.getParameter("lName");
String sqlCheck = "Select * from [UAP].[dbo].[UAP_EMPLOYEE] where EMP_EMPLOYEE_ID = "empId" ";
PreparedStatement prpStatementCheck = conn.prepareStatement(sqlCheck);
prpStatementCheck.setInt(1, Integer.parseInt(empId));
prpStatementCheck.setString(2, fName);
prpStatementCheck.setString(3, lName);
ResultSet rsCheck=prpStatementCheck.executeQuery();
String check=null;
boolean exists = false;
while(rsCheck.next())
{
Statement stmt = conn.createStatement();
String sql= "UPDATE [UAP].[dbo].[UAP_EMPLOYEE] SET EMP_EMPLOYEE_ID="+empId+", EMP_FNAME='"+fName+"', EMP_LNAME='"+lName+"' WHERE EMP_EMPLOYEE_ID= ?";
stmt.executeUpdate(sql);
exists = true;
}
if(!exists)
{
String sql2 = "INSERT INTO [UAP].[dbo].[UAP_EMPLOYEE] (EMP_EMPLOYEE_ID, EMP_FNAME, EMP_LNAME ) VALUES (?,?,?)";
PreparedStatement prpStatement1 = conn.prepareStatement(sql2);
prpStatement1.setInt(1, Integer.parseInt(empId));
prpStatement1.setString(2, fName);
prpStatement1.setString(3, lName);
prpStatement1.execute();
prpStatement1.close();
}
%>
As EMP_EMPLOYEE_ID is an INTEGER field you will need to use:
prpStatementCheck.setInt(1, Integer.parseInt(empId));
Also, you can remove the quotes around this field for the UPDATE string:
String sql= "UPDATE [UAP_EMPLOYEE] SET EMP_EMPLOYEE_ID=" + empId + ", EMP_FNAME='" + fName+"', EMP_LNAME='" + lName + "' WHERE EMP_EMPLOYEE_ID= " + empId;
Again for prpStatement1:
prpStatement1.setInt(1, Integer.parseInt(empId));