Inserting data in MySql Workbench - java

String query = "INSERT INTO 'registration'.'regg' ('fname','lname','address','gender','email','phone','username','password') VALUES (?,?,?,?,?,?,?,?);" ;
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, username, password);
pst = conn.prepareStatement(query);
pst.setString(1, txtfname.getText());
pst.setString(2, txtlname.getText());
pst.setString(3, txtadd.getText());
pst.setString(4, cmbGender.getSelectedItem().toString());
pst.setString(5, txtEmail.getText());
pst.setString(6, txtphone.getText());enter code here
pst.setString(7, txtuser.getText());
pst.setString(8, txtpass.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Register successfully");
This is the error
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''registration'.'regg'
('fname','lname','address','gender','email','phone','usern' at line

Could you please try this
String query = "INSERT INTO regg (fname, lname, address, gender, email, phone, username, password) VALUES (?,?,?,?,?,?,?,?)";
Hope this will work for you

Related

Using a prepared statement with auto increment field

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

Error : Index parameter out of range

I want to insert primary key of selected item of combo box
but I got this error Parameter index out of range(12 > number of parameter which is 0)".
I really don't know how to fix this.
Here is my code:
String valueTrainer = "kosong";
try
{
String sql2 = "Insert into ahli (MemberID, TrainerID, Name, ICNumber, Address, Nationality,"
+ "PhoneNumber, Email, EmergencyPerson, EmergencyContact, DateReg, MemberTypeID) "
+ "values(?,?,?,?,?,?,?,?,?,?,?,?)";
pst = conn.prepareStatement(sql2);
pst.setString(1, MemberIDTextField.getText());
pst.setString(2, valueTrainer);
pst.setString(3, NameTextField.getText());
pst.setString(4, jTextField1.getText());
pst.setString(5, AddressTextArea.getText());
//Nationality combo box
String nationalityList = NationalityComboBox.getSelectedItem().toString();
pst.setString(6, nationalityList);
pst.setString(7, PhoneNumberTextField.getText());
pst.setString(8, EmailTextField.getText());
pst.setString(9, EmerContactPersonTextField.getText());
pst.setString(10, EmerContactNumberTextField.getText());
//Date Chooser
pst.setString(11, ((JTextField)MemberDateChooser.getDateEditor().getUiComponent()).getText());
//membertype combobox
// problem start from here, I think..
String memberTypeList = MemberTypeComboBox.getSelectedItem().toString();
String sql1 ="Select MemberTypeID from jeniskeahlian where Type = '"+memberTypeList+"' " ;
pst = conn.prepareStatement(sql1);
rs = pst.executeQuery();
while(rs.next()){
String memberType = rs.getString("MemberTypeID");
pst.setString(12, memberType);
}
pst.execute();
JOptionPane.showMessageDialog(null, "New member has been added");
} catch (SQLException | HeadlessException e) {
JOptionPane.showMessageDialog(null, e);
}
You are not using pst properly.
same named reference on prepared statement can not be used on different sql statement unless one is used and closed properly. Prepare, set, execute, close on one statement, and then repeat the same on another statement.
Change your code as below.
try
{
String memberTypeList = MemberTypeComboBox.getSelectedItem().toString();
String sql1 ="Select MemberTypeID
from jeniskeahlian
where Type = ? " ;
pst = conn.prepareStatement(sql1);
pst.setString( 1, memberTypeList );
rs = pst.executeQuery();
String memberType = "";
while(rs.next()){
memberType = rs.getString("MemberTypeID");
}
rs.close();
pst.close();
String sql2 = "Insert into ahli (MemberID, TrainerID, Name,
ICNumber, Address, Nationality,
PhoneNumber, Email, EmergencyPerson,
EmergencyContact, DateReg, MemberTypeID)
values(?,?,?,?,?,?,?,?,?,?,?,?)";
pst = conn.prepareStatement(sql2);
pst.setString(1, MemberIDTextField.getText());
pst.setString(2, valueTrainer);
pst.setString(3, NameTextField.getText());
pst.setString(4, jTextField1.getText());
pst.setString(5, AddressTextArea.getText());
//Nationality combo box
String nationalityList = NationalityComboBox.getSelectedItem().toString();
pst.setString(6, nationalityList);
pst.setString(7, PhoneNumberTextField.getText());
pst.setString(8, EmailTextField.getText());
pst.setString(9, EmerContactPersonTextField.getText());
pst.setString(10, EmerContactNumberTextField.getText());
//Date Chooser
pst.setString(11, ((JTextField)MemberDateChooser
.getDateEditor()
.getUiComponent()).getText());
pst.setString(12, memberType);
pst.execute();
JOptionPane.showMessageDialog(null, "New member has been added");
} // try
While your insert statement seems properly populated, in the while-loop you rare trying to execute a select statement which has no parameters, so that pst.setString(12,memberType) fails.
String sql1 ="Select MemberTypeID from jeniskeahlian where Type = '"+memberTypeList+"' " ; //no ? in this query
Before you execute the query you should have set all the values for all the parameters.

Number of query values and destination fields are not the same in Java

I have a prepardStatement which should perform an insert to MS Access
Below is the SQL
INSERT INTO DonorDetails (Title,FirstName,LastName,[IC NUMBER],[OLD IC NUMBER],Gender,DOB,COUNTRY,Race,[Address 1],[Address 2],[Address 3],[Address 4],City,State,Postcode,[TEL HSE],[TEL HP],[TEL OFF],[Fax Number],Email,Language,[Donation Amount],Frequency,Bank,MODE,[CHQ/MO/PO],[CREDIT CARD],[NAME OF CARD HOLDER],Expiry,[ISSUING BANK],[ACCOUNT NUMBER],CAMPAIGN,[SERIAL NO],[EVENT CODE],[AGENT ID],Channel,[SOURCE CODE],[SIGNUP DATE],Remarks, [Date Processed])values (?,?,?.?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
During insert I get the following error
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Number of query values and destination fields are not the same.
This is how I execute my code which I believe the number of fields / columns is 41
Connection conn = Connect.ConnectDB();
System.out.println(sql);
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, salutation);
pst.setString(2, txtFirstName.getText());
pst.setString(3, txtLastName.getText());
pst.setString(4, newID);
pst.setString(5, oldID);
pst.setString(6, String.valueOf(cbGender.getSelectedItem()));
pst.setString(7, dobDate);
pst.setString(8, String.valueOf(cbNationality.getSelectedItem()));
pst.setString(9, race);
pst.setString(10, txtAddress.getText());
pst.setString(11, txtAddress2.getText());
pst.setString(12, txtAddress3.getText());
pst.setString(13, txtAddress4.getText());
pst.setString(14, txtCity.getText());
pst.setString(15, String.valueOf(cbState.getSelectedItem()));
pst.setString(16, txtPostCode.getText());
pst.setString(17, txtHomePhone.getText());
pst.setString(18, txtMobilePhone.getText());
pst.setString(19, txtOfficePhone.getText());
pst.setString(20, txtFax.getText());
pst.setString(21, txtEmail.getText());
pst.setString(22, txtLanguage.getText());
pst.setInt(23, amount);
pst.setString(24, frequency);
pst.setString(25, bankName);
pst.setString(26, mode);
pst.setString(27, prependNo + txtRefNo.getText());
pst.setString(28, cardNumber);
pst.setString(29, cardName);
pst.setString(30, cardExpiry);
pst.setString(31, issuingBank);
pst.setString(32, accountNumber);
pst.setString(33, String.valueOf(cbCampaign.getSelectedItem()));
pst.setString(34, lblSerialCode.getText()
+ txtSerialNumber.getText());
pst.setString(35, txtTeritoryCode.getText());
pst.setString(36, txtAgentID.getText());
pst.setString(37, String.valueOf(cbChannel.getSelectedItem()));
pst.setString(38, "OPTIMO");
pst.setString(39, df.format(signUpDate.getDate()));
pst.setString(40, textField.getText());
pst.setString(41, processedDate);
pst.execute();
I am unable to find what is wrong with the above code.

unable to spot the SQL syntax error

whenever i try to insert, delete and update i get the following syntax error. but after I close the exception jdialog and restart the application the data is either inserted, update and deleted
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your mariaDB server for the right syntax to use near 'Customer' at line 1
Insert query
try {
String sql = "Insert into Customer(ID , FirstName, MiddleName, LastName, DOB, Gander, Address, City, PostCode) "
+ "values (?, AES_ENCRYPT(?, 'uk112'),AES_ENCRYPT(?, 'uk112'),"
+ "AES_ENCRYPT(?, 'uk112'),?,AES_ENCRYPT(?, 'uk112'),"
+ "AES_ENCRYPT(?, 'uk112'),AES_ENCRYPT(?, 'uk112'),"
+ "AES_ENCRYPT(?, 'uk112'))";
pst = newconn.prepareStatement(sql);
pst.setString(1, jTextFieldID.getText());
pst.setString(2, jTextFieldFirstname.getText());
pst.setString(3, jTextFieldMiddlename.getText());
pst.setString(4, jTextFieldLastname.getText());
pst.setString(5, ((JTextField)txt_Date.getDateEditor().getUiComponent()).getText());
pst.setString(6, Gander);
pst.setString(7, jTextFieldAddress.getText());
pst.setString(8, jTextFieldCity.getText());
pst.setString(9, jTextFieldPostcode.getText());
pst.execute();
newconn.close();
JOptionPane.showMessageDialog(null, "Saved");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
Update query
try{
String value1 = jTextFieldID.getText();
String value2 = jTextFieldFirstname.getText();
String value3 = jTextFieldMiddlename.getText();
String value4 = jTextFieldLastname.getText();
String value5 = ((JTextField)txt_Date.getDateEditor().getUiComponent()).getText();
String value6= Gander.toString();
String value7= jTextFieldAddress.getText();
String value8 = jTextFieldCity.getText();
String value9 = jTextFieldPostcode.getText();
String sql = "update Customer set FirstName= AES_ENCRYPT(?,'uk112'),"
+ "MiddleName= AES_ENCRYPT(?,'uk112'),"
+ "LastName= AES_ENCRYPT(?,'uk112'),"
+ "DOB=?,Gander= AES_ENCRYPT(?,'uk112'),"
+ "Address= AES_ENCRYPT(?,'uk112'),"
+ "City= AES_ENCRYPT(?,'uk112'),"
+ "PostCode= AES_ENCRYPT(?,'uk112') where ID=?";
pst = newconn.prepareStatement(sql);
pst.setString(1, value2);
pst.setString(2, value3);
pst.setString(3, value4);
pst.setString(4, value5);
pst.setString(5, value6);
pst.setString(6, value7);
pst.setString(7, value8);
pst.setString(8, value9);
pst.setString(9, value1);
pst.execute();
newconn.close();
JOptionPane.showMessageDialog(null, "Data is updated");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
Delete query
String sql = "delete from Customer Where ID =?";
try{
pst= newconn.prepareStatement(sql);
pst.setString(1, jTextFieldID.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "Deleted");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}

how to insert date in mysql using jsp?

this is my edited code...
java.sql.Timestamp sqlNow = new java.sql.Timestamp(new java.util.Date().getTime());
stmt = con.createStatement();
//stmt.executeUpdate("INSERT INTO cregn values('"+appno+"','"+usname+"','"+upwd +"','"+fname+"','"+mname+"','"+lname+"','"+dob+"','"+gend+"','"+faname+"','"+saddr+"','"+caddr+"','"+staddr +"','"+pin+"','"+cno+"','"+email+"','"+occ+"','"+secques+"','"+answer+"','Processing','"+sqlNow+"')");
pst = con.prepareStatement("INSERT INTO cregn (aplno, username, pwd, firstname,middlename,lastname, dob,gender, fathername, street,city,state, pincode, phone, email,occupation,secques,answer,dor) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
pst.setInt(1, appno);
pst.setString(2, usname);
pst.setString(3, upwd);
pst.setString(4, fname);
pst.setString(5, mname);
pst.setString(6, lname);
pst.setString(7, dob);
pst.setString(8, gend);
pst.setString(9, faname);
pst.setString(10, saddr);
pst.setString(11, caddr);
pst.setString(12, staddr);
pst.setString(13, pin);
pst.setString(14, cno);
pst.setString(15, email);
pst.setString(16, occ);
// pst.setString(17,ph);
pst.setString(17, secques);
pst.setString(18, answer);
pst.setTimestamp(19, sqlNow);
pst.executeUpdate();
out.println("Registration Successful for application " + appno);
} catch (Exception ee) {
out.println("Invalid Data! All fields are mandatory..." + ee.getMessage());
}
%>
after executing this code error displayed "Invalid Data! All fields are mandatory..data truncation"
You are not executing the statement.
You need to call executeUpdate
You have to call execute or executeUpdate on pst in order to actually do the work. E.g., at the end:
pst.executeUpdate();
All that the code you've shown does is prepare the statement for execution, it doesn't execute it. This is one of the main differences between PreparedStatement and Statement. In Statement, you pass the SQL to execute directly into executeUpdate (as seen in your commented-out line using stmt). With a PreparedStatement, you supply the SQL with ? as you've done, set those parameters, and then call executeUpdate (or execute), which you haven't done.
There is no executeUpdate() being called on pst.
use pst.executeUpdate(); to execute the query and make sure that in transaction use setAutoCommit(true) has to be called.

Categories