Im trying to create an application that allows users to create a profile however when im inserting into the DB I get the error shown above. I've had a look at similiar solutions but nothing seems to have worked.
The relevant code as it stands is;
//Invokes myConnection class to link to DB
Connection con = myConnection.getConnection();
PreparedStatement ps;
try
{
//Adds the selected text to DB
ps = con.prepareStatement("INSERT INTO `user`(`username`, `realname`, `password`, `email`, `gym`, `belt`, `dateofbirth`, `profilepic`, `biography`, `motto`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
ps.setString(1, jTextFieldUsername.getText());
ps.setString(2, jTextFieldName.getText());
ps.setString(3, String.valueOf(jPasswordFieldPass.getPassword()));
ps.setString(4, jTextFieldEmail.getText());
ps.setString(5, jTextFieldGym.getText());
ps.setString(6, jComboBoxBelt.toString());
ps.setDate(7, convertUtilDateToSqlDate(jDateChooserDOB.getDate()));
InputStream img = new FileInputStream(new File(imagePath));
ps.setBlob(8, img);
if(ps.executeUpdate() != 0)
{
JOptionPane.showMessageDialog(null, "Account Created!");
}
else
{
JOptionPane.showMessageDialog(null, "Oops! Something went wrong!");
}
ps.setString(9, jTextAreaBiography.getText());
ps.setString(10, jTextAreaMotto.getText());
}
catch (Exception ex)
{
Logger.getLogger(RegisterPage.class.getName()).log(Level.SEVERE, null, ex);
}
Sorry if this is straight forward and thanks in advance for your help!
Edit: Answered simply, thanks was having a complete brainfart there.
The problem in your code is,
You have to set all the values for the parameters and then use execute statement.
your code should be like this.
ps = con.prepareStatement("INSERT INTO `user`(`username`, `realname`, `password`, `email`, `gym`, `belt`, `dateofbirth`, `profilepic`, `biography`, `motto`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
ps.setString(1, jTextFieldUsername.getText());
ps.setString(2, jTextFieldName.getText());
ps.setString(3, String.valueOf(jPasswordFieldPass.getPassword()));
ps.setString(4, jTextFieldEmail.getText());
ps.setString(5, jTextFieldGym.getText());
ps.setString(6, jComboBoxBelt.toString());
ps.setDate(7, convertUtilDateToSqlDate(jDateChooserDOB.getDate()));
InputStream img = new FileInputStream(new File(imagePath));
ps.setBlob(8, img);
ps.setString(9, jTextAreaBiography.getText());
ps.setString(10, jTextAreaMotto.getText());
if(ps.executeUpdate() != 0)
{
JOptionPane.showMessageDialog(null, "Account Created!");
}
else
{
JOptionPane.showMessageDialog(null, "Oops! Something went wrong!");
}
You are running ps.executeUpdate() without setting parameters 9 and 10.
Move these lines before if(ps.executeUpdate() != 0):-
ps.setString(9, jTextAreaBiography.getText());
ps.setString(10, jTextAreaMotto.getText());
Related
Ok, I want to preface. I have searched through multiple people having this issue and none of that seems to be my problem.
String Statement = "INSERT INTO DAISYEMPLOYEE"
+ "(SSN, FNAME, MINIT, LNAME, ADDRESS, DATEHIRED, PAY, PHONE#) VALUES "
+ "( ?, ?, ?, ?, ?, ?, ?, ?)";
JOptionPane.showMessageDialog(frame, Statement, "Daisy Imports", 3);
try {
PreparedStatement PST = connection.prepareStatement(Statement);
PST.setInt(1, 11);
PST.setString(2, "NAME");
PST.setString(3, "a");
PST.setString(4, "asdasd");
PST.setString(5, "123 hobo street");
PST.setString(6, "2017-05-06 ");
PST.setString(7, "8.5");
PST.setString(8, "1231231234");
PST.execute();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(frame, "PUERILE CAPTION REMOVED", "Daisy Imports", 3);
Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex);
} // try
I totally have parameters, I have no idea whats happening.
I am having trouble with a java file when trying to run it on tomcat. I am suppose to be able to edit records that I put in a database, when I edit the records they do nothing. When I try to edit the records Tomcat throws me this 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 'WHERE cus_id =
'13'' at line 1
I figure this is the code that has the error because it has all of the SQL commands. The delete function works. I just can not edit a record...
Thanks for the help!
package crud.data;
import java.sql.*;
import java.util.ArrayList;
import crud.business.Customer;
public class CustomerDB
{
//insert method (pass customer object to parameter customer)
public static int insert(Customer customer)
{
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
//comment
String query
= "INSERT INTO customer (cus_fname, cus_lname, cus_street, cus_city,
cus_state, cus_zip, cus_phone, cus_email, cus_balance, cus_total_sales,
cus_notes) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
try {
ps = connection.prepareStatement(query);
ps.setString(1, customer.getFname());
ps.setString(2, customer.getLname());
ps.setString(3, customer.getStreet());
ps.setString(4, customer.getCity());
ps.setString(5, customer.getState());
ps.setString(6, customer.getZip());
ps.setString(7, customer.getPhone());
ps.setString(8, customer.getEmail());
ps.setString(9, customer.getBalance());
ps.setString(10, customer.getTotalSales());
ps.setString(11, customer.getNotes());
return ps.executeUpdate();
} catch (SQLException e){
System.out.println(e);
return 0;
} finally {
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
//update method
public static int update(Customer customer)
{
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
String query = "UPDATE customer SET "
+ "cus_fname = ?, "
+ "cus_lname = ?, "
+ "cus_street = ?, "
+ "cus_city = ?, "
+ "cus_state = ?, "
+ "cus_zip = ?, "
+ "cus_phone = ?, "
+ "cus_email = ?, "
+ "cus_balance = ?, "
+ "cus_total_sales = ?, "
+ "cus_notes = ?, "
+ "WHERE cus_id = ?";
try {
ps = connection.prepareStatement(query);
ps.setString(1, customer.getFname());
ps.setString(2, customer.getLname());
ps.setString(3, customer.getStreet());
ps.setString(4, customer.getCity());
ps.setString(5, customer.getState());
ps.setString(6, customer.getZip());
ps.setString(7, customer.getPhone());
ps.setString(8, customer.getEmail());
ps.setString(9, customer.getBalance());
ps.setString(10, customer.getTotalSales());
ps.setString(11, customer.getNotes());
ps.setString(12, customer.getId());
return ps.executeUpdate();
} catch (SQLException e) {
System.out.println(e);
return 0;
} finally {
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
}
You have a comma , on the last value
+ "cus_notes = ?, "
so replace with
+ "cus_notes = ? "
Line 64 : remove the comma from + "cus_notes = ?, ".
It is syntax error as shown in your console log.
You have comma at the end of last value,remove it and give a try
"cus_notes = ?"
You should post more full of errors, it is easier to identify where mistakes, now according to your tip is SQL syntax errors.
I'm having problems in my program. Well, here's my code:
JButton btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String query = "INSERT INTO GuestList (id, Title, FirstName, MiddleName, LastName, Address, ContactNo, Occupation) values (?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement pst = conn.prepareStatement(query);
count++;
pst.setString(1, String.valueOf(textField.setText(count + "")); //<<--This is my problem
pst.setString(2, comboBox.getToolTipText());
pst.setString(3, fNameTextField.getText());
pst.setString(4, mNameTextField.getText());
pst.setString(5, lNameTextField.getText());
pst.setString(6, addressTextPane.getText());
pst.setString(7, contactNoTextField.getText());
pst.setString(8, occupationTextField.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "Data Saved!");
pst.close();
}catch(Exception e){
}
}
});
I'm having an auto increment in the line that has a comment in it. It says that " - Syntax error, insert ")" to complete Expression" and "The method valueOf(Object) in the type String is not applicable for the arguments (void)"
What should I do to get rid of these? Can someone help me? Thank you. :)
for every opening group like this ( you will need a closing one like that )
you have here 3 open and 2 closed....
pst.setString(1, String.valueOf(textField.setText(count + ""));
so you are missing one )
try:
pst.setString(1, String.valueOf(textField.setText(count + "")));
In my database I have two tables called car and ad. In car i have a foreign key referencing the adId value in ad. When i run my code, i don't get any errors, but data is only inserted into ad, not car. Any suggestions? Here's my code:
public void createAd(Ad ad, Car car) {
try {
Class.forName("org.postgresql.Driver");
if (con != null) {
ps = con.prepareStatement("INSERT INTO \"ad\"(\"title\", \"description\", \"author\", \"image\") VALUES (?, ?, ?, ?)");
ps.setString(1, ad.getTitle());
ps.setString(2, ad.getDescription());
ps.setString(3, ad.getAuthor());
ps.setBytes(4, ad.getImage());
ps.executeQuery();
ps = con.prepareStatement("SELECT currval('\"ad_adId_seq\"');");
rs = ps.executeQuery();
rs.next();
int adId = rs.getInt("currval");
ps = con.prepareStatement("INSERT INTO \"ad\"(\"adId\") VALUES (?);");
ps.setInt(1, adId);
ps.executeUpdate();
ad.setAdId(adId);
ps = con.prepareStatement("INSERT INTO \"car\"(\"distanceTraveled\", \"age\", \"condition\", \"vin\", \"brand\", \"price\", \"ad_adId\") VALUES (?, ?, ?, ?, ?, ?, ?)");
ps.setInt(1, car.getDistanceTraveled());
ps.setInt(2, car.getAge());
ps.setString(3, car.getCondition());
ps.setString(4, car.getVIN());
ps.setString(5, car.getBrand());
ps.setInt(6, car.getPrice());
ps.setInt(6, adId);
ps.executeQuery();
car.setAdId(adId);
}
} catch (Exception ex) {
System.out.println(ex);
}
}
There is an error in your last query :
ps.setInt(7, adId);
instead of
ps.setInt(6, adId);
I suggest that you should take a look at spring-database. Using JdbcTemplate will reduce a lot of the JDBC boiler plate code and more important will take care for a lot of jdbc connection leaks worries for you.
If you sill need to use plain JDBC, you need to properly initialize the connection object and use update instead of query, when using update statements.
Also you need to properly close the statement objects that were created.
You should do something similar to the below code:
Connection con = null;
PrepareStatement ps1 = null;
PrepareStatement ps2 = null;
PrepareStatement ps3 = null;
PrepareStatement ps4 = null;
ResultSet rs = null;
String url = "jdbc:postgresql://localhost/dbName";
String user = "userName";
String password = "userPass";
try {
con = DriverManager.getConnection(url, user, password);
ps1 = con.prepareStatement("INSERT INTO \"ad\"(\"title\", \"description\", \"author\", \"image\") VALUES (?, ?, ?, ?)");
ps1.setString(1, ad.getTitle());
ps1.setString(2, ad.getDescription());
ps1.setString(3, ad.getAuthor());
ps1.setBytes(4, ad.getImage());
ps1.executeUpdate();
ps2 = con.prepareStatement("SELECT currval('\"ad_adId_seq\"');");
rs = ps2.executeQuery();
if(rs.next())
int adId = rs.getInt("currval");
}
ps3 = con.prepareStatement("INSERT INTO \"ad\"(\"adId\") VALUES (?);");
ps3.setInt(1, adId);
ps3.executeUpdate();
ad.setAdId(adId);
ps4 = con.prepareStatement("INSERT INTO \"car\"(\"distanceTraveled\", \"age\", \"condition\", \"vin\", \"brand\", \"price\", \"ad_adId\") VALUES (?, ?, ?, ?, ?, ?, ?)");
ps4.setInt(1, car.getDistanceTraveled());
ps4.setInt(2, car.getAge());
ps4.setString(3, car.getCondition());
ps4.setString(4, car.getVIN());
ps4.setString(5, car.getBrand());
ps4.setInt(6, car.getPrice());
ps4.setInt(7, adId);
ps4.executeUpdate();
car.setAdId(adId);
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(getClass().getName());
lgr.log(Level.SEVERE, "Unable to execute updates", ex);
} finally {
try {
if (rs != null)
rs.close();
if (ps1 != null)
ps1.close();
if (ps2 != null)
ps2.close();
if (ps3 != null)
ps3.close();
if (ps4 != null)
ps4.close();
if (con != null)
con.close();
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(getClass().getName());
lgr.log(Level.WARNING, "Unable to close the connection", ex);
}
}
I get that code:
#Override
public void bulkInsert(Collection<SortingPlanData> data, SortingPlan plan) {
Session session = getEntityManager().unwrap(Session.class);
SessionFactoryImplementor sessionFactoryImplementation = (SessionFactoryImplementor) session
.getSessionFactory();
ConnectionProvider connectionProvider = sessionFactoryImplementation
.getConnectionProvider();
String sql = "insert into SORTING_PLAN_DATA (ACHEMINEMENT, ANCIEN_GROUPE_SERVICE_LABELS, BAG_ID, BARCODE_ID, CHRONOSERVICE, CODE_ROUTING, D_DEPOT_NUMBER, D_SORT, DELIVERY_STATION, DESCRIPTION, DESTINATION_PAYS_ALPHA2_ISO, DESTINATION_PAYS_ALPHA3_ISO, DESTINATION_PAYS_NUM_ISO,"
+ " DIST, GROUPE_SERVICE_LABELS, GROUPING_PRIORITY, LIVRAISON, O_SORT, ORIGINE_PAYS_ALPHA2_ISO, ROUTING_PLACES, S_SORT, SENDING_DATE, SERVICE_CODES, SITE_IATA, SORTING_PLAN_ID, TYPE_EXPORT, VILLE, ZIP_MAX, ZIP_MIN) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
Transaction tx = session.getTransaction();
final int batchSize = 500;
int count = 0;
try {
tx.begin();
Connection con = connectionProvider.getConnection();
PreparedStatement ps = con.prepareStatement(sql);
for (SortingPlanData spd : data) {
ps.setString(1, spd.getAcheminement());
ps.setString(2, spd.getAncienGroupeServiceLabels());
ps.setString(3, spd.getBagId());
ps.setString(4, spd.getBarcodeId());
ps.setString(5, spd.getChronoservice());
ps.setString(6, spd.getCodeRouting());
ps.setString(7, spd.getDDepotNumber());
ps.setString(8, spd.getDSort());
ps.setString(9, spd.getDeliveryStation());
ps.setString(10, spd.getDescription());
ps.setString(11, spd.getDestinationPaysAlpha2Iso());
ps.setString(12, spd.getDestinationPaysAlpha3Iso());
ps.setInt(13, spd.getDestinationPaysNumIso());
ps.setString(14, spd.getDist());
ps.setString(15, spd.getGroupeServiceLabels());
ps.setString(16, spd.getGroupingPriority());
ps.setString(17, spd.getLivraison());
ps.setString(18, spd.getOSort());
ps.setString(19, spd.getOriginePaysAlpha2Iso());
ps.setString(20, spd.getRoutingPlaces());
ps.setString(21, spd.getSSort());
ps.setDate(22, new java.sql.Date(System.currentTimeMillis()));
ps.setString(23, spd.getServiceCodes());
ps.setString(24, spd.getSiteIata());
ps.setLong(25, plan.getId());
ps.setString(26, spd.getTypeExport());
ps.setString(27, spd.getVille());
ps.setString(28, spd.getZipMin());
ps.setString(29, spd.getZipMax());
ps.addBatch();
count++;
if (count % batchSize == 0) {
ps.executeBatch();
LOGGER.info(count + " lines inserted do far in");
}
}
ps.executeBatch(); // insert remaining records
ps.close();
con.close();
} catch (SQLException e) {
tx.rollback();
throw new HibernateException(e.getMessage(), e.getCause());
}
tx.commit();
}
The bulkInsert method is called from a class which itself is annotated with #Transactional, and of course, I get an Exception on tx.begin():
org.hibernate.TransactionException: nested transactions not supported
Problem is, I have no idea on how to retrieve the existing transaction and transmit it to my bulkInsert() method. Any leads?
I'm using Java 6, with Hibernate 4, Spring 3.2.3 on a Sybase 15.5 database.
You are making it way to complex, use a [JdbcTemplate][1] which uses the same DataSourceas your EntityManagerFactory. This will obtain the current connection and automatically participate in the already ongoing transaction. Next to that it will greatly simplify your code.
#Autowired
private JdbcTemplate jdbcTemplate
#Override
public void bulkInsert(Collection<SortingPlanData> data, SortingPlan plan) {
String sql = "insert into SORTING_PLAN_DATA (ACHEMINEMENT, ANCIEN_GROUPE_SERVICE_LABELS, BAG_ID, BARCODE_ID, CHRONOSERVICE, CODE_ROUTING, D_DEPOT_NUMBER, D_SORT, DELIVERY_STATION, DESCRIPTION, DESTINATION_PAYS_ALPHA2_ISO, DESTINATION_PAYS_ALPHA3_ISO, DESTINATION_PAYS_NUM_ISO,"
+ " DIST, GROUPE_SERVICE_LABELS, GROUPING_PRIORITY, LIVRAISON, O_SORT, ORIGINE_PAYS_ALPHA2_ISO, ROUTING_PLACES, S_SORT, SENDING_DATE, SERVICE_CODES, SITE_IATA, SORTING_PLAN_ID, TYPE_EXPORT, VILLE, ZIP_MAX, ZIP_MIN) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
jdbcTemplate.batchUpdate(sql, data, 500, new ParameterizedPreparedStatementSetter<SortingPlanData>() {
public void setValues(PreparedStatement ps, SortingPlanData spd) throws SQLException {
ps.setString(1, spd.getAcheminement());
ps.setString(2, spd.getAncienGroupeServiceLabels());
ps.setString(3, spd.getBagId());
ps.setString(4, spd.getBarcodeId());
ps.setString(5, spd.getChronoservice());
ps.setString(6, spd.getCodeRouting());
ps.setString(7, spd.getDDepotNumber());
ps.setString(8, spd.getDSort());
ps.setString(9, spd.getDeliveryStation());
ps.setString(10, spd.getDescription());
ps.setString(11, spd.getDestinationPaysAlpha2Iso());
ps.setString(12, spd.getDestinationPaysAlpha3Iso());
ps.setInt(13, spd.getDestinationPaysNumIso());
ps.setString(14, spd.getDist());
ps.setString(15, spd.getGroupeServiceLabels());
ps.setString(16, spd.getGroupingPriority());
ps.setString(17, spd.getLivraison());
ps.setString(18, spd.getOSort());
ps.setString(19, spd.getOriginePaysAlpha2Iso());
ps.setString(20, spd.getRoutingPlaces());
ps.setString(21, spd.getSSort());
ps.setDate(22, new java.sql.Date(System.currentTimeMillis()));
ps.setString(23, spd.getServiceCodes());
ps.setString(24, spd.getSiteIata());
ps.setLong(25, plan.getId());
ps.setString(26, spd.getTypeExport());
ps.setString(27, spd.getVille());
ps.setString(28, spd.getZipMin());
ps.setString(29, spd.getZipMax());
}
});
}