unable to spot the SQL syntax error - java

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

Related

Inserting data in MySql Workbench

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

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.

MsAccess SQL Exception Too few parameters

Currently making a java program that grabs data off of a MSAccess Database and some of these errors are extremely frustrating. I keep getting this SQL.Exception : Too few parameters. Expected 1 error on the last remaining bugs in this program.
Little background on the db: It has 3 tables (A player table (11 columns), a team table (3 columns), and an Opponent table (6 columns).
These are both of the functions and I am fairly certain the problem lies in here somewhere
conn = Connect.ConnectDB();
String sql = "insert into Player ("+"PlayerLastName,"+"PlayerFirstName,"+"Position)"+ "values("+txtid.getText()+ ",'"+txtname.getText()+"','"+txtaddress.getText()+"')" ;
try{
pst = conn.prepareStatement(sql);
pst.executeQuery();
pst.setString(1, txtid.getText());
pst.setString(2, txtname.getText());
pst.setString(3, txtaddress.getText());
JOptionPane.showMessageDialog(null, txtid.getText() + " Saved");
UpdateJTable();
//conn.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
or this function
String sql = "select * from Player where PlayerLastName = " +txtid.getText()+ "";
String pine = null;
try{
pst = conn.prepareStatement(sql);
ResultSet res;
res = pst.executeQuery();
pine.equalsIgnoreCase(jTable1.getModel().getValueAt(rowsu, 10).toString());
while(res.next()){
JOptionPane.showMessageDialog(null, txtname + " " + txtid.getText() + " has a total of " +"4");//+ pine);//res.getInt("Penalties") );
}
UpdateJTable();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
For one thing, it looks like you're missing single quotes around the last name in the insert statement.
There may be other errors as well, that's just the first thing I noticed.
This should be pretty easy to debug if you just log the sql string before executing it.
EDIT
I think your calls to setString() are also a problem. Here is how you should do this:
conn = Connect.ConnectDB();
String sql = "insert into Player (PlayerLastName, PlayerFirstName, Position) values(?, ?, ?)";
try{
pst = conn.prepareStatement(sql);
pst.setString(1, txtid.getText());
pst.setString(2, txtname.getText());
pst.setString(3, txtaddress.getText());
pst.execute();
JOptionPane.showMessageDialog(null, txtid.getText() + " Saved");
UpdateJTable();
//conn.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}

How to insert the same record into two different table in java?

How can I insert records into two different table? I made two sql statement and it won't work.
private void cmdsubmitActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
String sql = "Insert into customer (Customer_ID,First_Name,Last_Name,Birthdate,Gender,Occupation,Address,Email,Contact,Status,Income,Amount,Term,Interest,Date_Applied,Purpose,Other) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
pst = conn.prepareStatement(sql);
pst.setString(1, txtID.getText());
pst.setString(2, txtfname.getText());
pst.setString(3, txtlname.getText());
pst.setString(4,((JTextField)birthdate.getDateEditor().getUiComponent()).getText());
String gender = cmbgender.getSelectedItem().toString();
pst.setString(5, gender);
pst.setString(6, txtoccupation.getText());
pst.setString(7, txtaddress.getText());
pst.setString(8, txtemailadd.getText());
pst.setString(9, txtcontact.getText());
String status = cmbstatus.getSelectedItem().toString();
pst.setString(10, status);
String income = cmbincome.getSelectedItem().toString();
pst.setString(11,income);
pst.setString(12, txtamount.getText());
String period = cmbperiod.getSelectedItem().toString();
pst.setString(13, txtloan.getText() + " " + period);
pst.setString(14, txtinterest.getText());
pst.setString(15, ((JTextField)datechooser.getDateEditor().getUiComponent()).getText());
String purpose = cmbpurpose.getSelectedItem().toString();
pst.setString(16, purpose);
pst.setString(17, txtother.getText());
Double balance = Double.parseDouble(txtamount.getText()) * Double.parseDouble(txtinterest.getText());
String s = "Insert into payments (Customer_ID,Customer_Name,Amount,Interest,To_Pay) values (?,?,?,?,?)";
pst = conn.prepareStatement(s);
pst.setString(1, txtID.getText());
pst.setString(2, txtfname.getText()+","+txtlname.getText());
pst.setString(3, txtamount.getText());
pst.setString(4, txtinterest.getText());
pst.setString(5, balance.toString());
pst.execute();
JOptionPane.showMessageDialog(null, "Record Save");
Menu menu = new Menu();
this.setVisible(false);
menu.setVisible(true);
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
The problem appears to be that you aren't calling pst.execute() before you call this line:
pst = conn.prepareStatement(s);
This is overwriting your previous pst variable; creating a new PreparedStatement.
I'm not entirely sure about that API, but it seems like you have one execute for two statements. Also, you should consider making a function if a good chunk of the code is exactly the same. Less places to maintain

Categories