I have:
String query = "INSERT INTO Basestations VALUES(?, ?, ?, ?, ?, ?, ?,"
+ "?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement prep = conn.prepareStatement(query);
prep.setInt(1, profile.getNetworkId());
prep.setInt(2, profile.getBaseStationId());
prep.setInt(8, profile.getLoadLevel());
prep.setInt(11, profile.getPositionX());
prep.setInt(12, profile.getPositionY());
prep.setInt(13, profile.getPort());
prep.setDouble(3, profile.getSignalStrength());
prep.setDouble(4, profile.getFrequency());
prep.setDouble(6, profile.getMaxBitrate());
prep.setDouble(7, profile.getGuaranteedBitrate());
prep.setDouble(10, profile.getRange());
prep.setString(5, profile.getNetworkType());
prep.setString(9, profile.getProvider());
prep.setString(14, profile.getCharging());
prep.setBoolean(15, true);
prep.executeUpdate(query);
and i am getting:
INFO: SQL Exception:
INFO: State : 42000
INFO: Message: 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 '?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' at line 1
INFO: Error : 1064
what could be wrong?
You're passing an string representing an invalid SQL statement to the executeUpdate() method when you don't need to. Try just doing prep.executeUpdate();.
In your last line you don't need pass the variable query.
So change
prep.executeUpdate(query);
For:
prep.executeUpdate();
The main error is here:
// incorrect
prep.executeUpdate(query);
// correct
prep.executeUpdate();
But please try to put your SQL in the following form:
UPDATE table_name(field1, field2, field3) VALUES(?, ? ,?)
This will prevent your code from breaking if there is an update to the table.
Related
String sql = " INSERT INTO `tblservice` (`ServiceID`,`accountID`, `Kind`, `Description`, `Price`, "
+ "`Quantity`, `Total`, `DateAndTime`) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement pstm = conn.prepareStatement(sql);
pstm.setInt(1, this.accountID);
pstm.setString(2, "" + SelectionBox.getSelectedItem());
pstm.setString(3, desc);
pstm.setFloat(4, Float.parseFloat(PriceTF.getText()));
pstm.setFloat(5, Float.parseFloat(QuantityTF.getText()));
pstm.setFloat(6, this.getTotal());
pstm.setDate(7, dateAdded);
pstm.executeUpdate();
Error
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?, ?, ?, ?, ?, ?, ?)' at line 1
Instead of make NULL in your query VALUES (NULL, ...) use setNull for example :
pstm.setNull(1, java.sql.Types.INTEGER);
It will take the type, of your field, in this example i consider it is a java.sql.Types.INTEGER it can be java.sql.Types.VARCHAR or any sql type
So your query should be like this :
String sql = "INSERT INTO tblservice (ServiceID, accountID, Kind, Description,
Price, Quantity, Total, DateAndTime)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement pstm = conn.prepareStatement(sql);
pstm.setNull(1, java.sql.Types.INTEGER);
pstm.setInt(2, this.accountID);
....
in my local system it working with out any problem. my local system is windows 7 but exception coming randomly in production server which is linux.
i am sharing code please guide me. this exception coming in same location only what is the reason.
Exception occurring at saveOrUpdate method
billSubmissionBean.setMasterProviderId(String.valueOf(masterProvider.getMasterProviderId()));
masterBill.setMasterProvider(masterProvider);
masterBill.setTransactionType(transactionType);
billSubmissionDao.save(masterBill, MasterBill.class);
BillSubmission billSubmission = getBillSubmissionFromBean(billSubmissionBean, user);
billSubmission.setMasterBill(masterBill);
billSubmission.setBillSubmissionNumber(masterBill.getBillSubmissionNumber());
billSubmission.setMasterProviderId(masterProvider.getMasterProviderId());
billSubmission.setTransactionType(transactionType);
billSubmission.setApiFlg(Boolean.TRUE);
if(StringUtils.strToBoolean(billSubmissionBean.getGenerateBillDocument())) {
billSubmission.setBillDocumentFlg(Boolean.TRUE);
}
billSubmissionDao.save(billSubmission, BillSubmission.class);
List<BillingServiceBean> billingServicesList = billSubmissionBean.getServices();
if(billingServicesList != null) {
List<BillService> billServicesList = new ArrayList<BillService>();
for (BillingServiceBean billServiceBean : billingServicesList) {
BillService billService = getBillServiceFromBillServiceBean(billServiceBean, user, billSubmissionBean.getGenerateBillDocument());
billService.setBillSubmission(billSubmission);
billServicesList.add(billService);
}
log.info("Bill services size : " + billServicesList.size());
if(billingServicesList.size() > 0) {
billSubmissionDao.saveOrUpdateAll(billServicesList);//this location
}
}
excption :
org.springframework.jdbc.UncategorizedSQLException: Hibernate
flushing: could not insert: [gov.nysif.model.BillService];
uncategorized SQLException for SQL [insert into nysif.bill_service
(bill_submission_id, service_place, service_procedure,
service_modifiers, dx_pointer, service_days, billed_amount,
service_ndc, service_ndc_qty, anesthesia_start, anesthesia_end,
revenue_code, dos_from_dt, dos_to_dt, created_dt, created_user,
modified_dt, modified_user, non_covered_charges, bill_service_id)
values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)];
SQL state [55000]; error code [0]; This statement has been closed.;
nested exception is org.postgresql.util.PSQLException: This statement
has been closed. at
org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:83)
at
org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
at
org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
at
org.springframework.orm.hibernate3.HibernateTransactionManager.convertJdbcAccessException(HibernateTransactionManager.java:726)
I am getting -845 SQL codes on a table insert:
nested exception is org.springframework.jdbc.UncategorizedSQLException: PreparedStatementCallback; uncategorized SQLException for SQL
[INSERT INTO PIM30_POL_DETAILS VALUES(PREVIOUS VALUE FOR PIM_ORDER_ID_SEQ, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)];
SQL state [51035]; error code [-845]; DB2 SQL Error: SQLCODE=-845, SQLSTATE=51035, SQLERRMC=SHELTRU.PIM_ORDER_ID_SEQ, DRIVER=4.17.29; nested exception is com.ibm.db2.jcc.am.SqlException: DB2 SQL Error: SQLCODE=-845, SQLSTATE=51035, SQLERRMC=SHELTRU.PIM_ORDER_ID_SEQ, DRIVER=4.17.29] with root cause
com.ibm.db2.jcc.am.SqlException: DB2 SQL Error: SQLCODE=-845, SQLSTATE=51035, SQLERRMC=SHELTRU.PIM_ORDER_ID_SEQ, DRIVER=4.17.29
The Java code for this is:
#Transactional
public String insertIntoDatabase(final List<Policy> pols, final InspectionOrder order, final OrderReason reason){
String toReturn = PolicyDAO.transactionTemplate.execute(new TransactionCallback<String>() {
#Override
public String doInTransaction(TransactionStatus status) {
SqlParameterSource params = new BeanPropertySqlParameterSource(order);
PolicyDAO.namedParemeterJdbcTemplate.update(Queries.getInsertInspOrder(), params);
for(Policy p : pols){
params = new BeanPropertySqlParameterSource(p);
PolicyDAO.namedParemeterJdbcTemplate.update(Queries.getInsertPolDetails(), params);
}
return "Successfully ordered inspection(s)";
}
});
if(toReturn.equals("Successfully ordered inspection(s)")) return toReturn;
else return "Failed to order inspection(s)";
}
Both INSERT statements use a sequence, the first one uses NEXT VALUE FOR PIM_ORDER_ID_SEQ and the second one uses PREVIOUS VALUE FOR PIM_ORDER_ID_SEQ. I presume that the second insertion is being called before the first insertion is finished as I only get the error 5-10% of the time.
What can I do to combat this?
I am writing an android app. I have an String of base64-encoded data, and I want to store it in my sqlite3 table. I am trying to do the following:
SQLiteDatabase db = new MyDatabase(MyApplication.getContext()).getWritableDatabase();
SQLiteStatement stmt = db.compileStatement("insert into MyTable values($next_id, ?, ?, ?, ?, ?, ?);");
stmt.bindLong(1, id);
stmt.bindString(2, someString);
stmt.bindLong(3, someLong);
stmt.bindLong(4, anotherLong);
stmt.bindLong(5, moreLong);
stmt.bindString(6, base64Data); // the field in question
stmt.execute();
But I get this error:
(1299) abort at 19 in [insert into MyTable values($next_id, ?, ?, ?, ?, ?, ?);]: NOT NULL constraint failed: MyTable.base64Data
MyTable.base64Data schema is: base64Data text NOT NULL
I can see in my debugger that base64Data is not null, so I think my query must not be formed correctly.
I also tried putting the last question mark in quotes:
SQLiteStatement stmt = db.compileStatement("insert into MyTable values($next_id, ?, ?, ?, ?, ?, \"?\");");
But that did not fix the error. What do I need to do?
You have seven parameters, but bind only six.
(If the first column should be autoincrementing, use NULL instead of $next_id.)
I get this error when im making a new character to my game, in the CreateCharHandler it sends "saveToDb(false);" but when im ingame with another char i manually created i can saveToDb(true); with no error. please help, why is this happening?
http://i56.tinypic.com/oh1pn5.png
SaveToDb method http://pastebin.com/9sT5XBxp
line 3514 is:
ResultSet rs = ps.getGeneratedKeys();
Thanks in advance!
Your SQLException clearly states that:
You need to specify Statement.RETURN_GENERATED_KEYS to the
Statement.executeUpdate() or Connection.prepareStatement().
This can be achieved as follows (adding an additional value on Connection.prepareStatement() method):
String SQL = ""; //whatever my String is
PreparedStatement ps = connection.prepareStatement(SQL, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, "value");
//Other necessary ps.setXXX() methods
//now update
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
The Statement.RETURN_GENERATED_KEYS is key here.
Hope this helps!
PS: Useful resource.
#Charlie berg, since you prefer being lazy, I changed line 13 of your code to include the Statement.RETURN_GENERATED_KEYS:
ps = con.prepareStatement("INSERT INTO characters (level, fame, str, dex, luk, `int`, exp, hp, mp, maxhp, maxmp, sp, ap, gm, skincolor, gender, job, hair, face, map, meso, hpMpUsed, spawnpoint, party, buddyCapacity, messengerid, messengerposition, mountlevel, mounttiredness, mountexp, equipslots, useslots, setupslots, etcslots, monsterbookcover, watchedcygnusintro, vanquisherStage, dojopoints, lastDojoStage, finishedDojoTutorial, vanquisherKills, matchcardwins, matchcardlosses, matchcardties, omokwins, omoklosses, omokties, givenRiceCakes, partyquestitems, jailtime, accountid, name, world) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS);
Also, Statement class is of package java.sql (make sure you import correctly). :-)
Oracle Documents:
If there is no indication that auto-generated columns should be made
available for retrieval, a call to Statement.getGeneratedKeys will
return a null ResultSet.
You should explicitly tell to JDBC That you want generated keys.
like this:
Statement stmt = conn.createStatement();
stmt.executeUpdate(sql,Statement.RETURN_GENERATED_KEYS);
or
conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
and then you can use getGeneratedKeys().