Java JDBC Error Insert into - java

Here is the code:
String sqlstatment = "INSERT INTO order (orderedBy, totalItems, totalPrice) "+
"VALUES (?, ?, ?);";
ResultSet keys = null;
try (
PreparedStatement stmt = conn.prepareStatement(sqlstatment, Statement.RETURN_GENERATED_KEYS);
){
stmt.setInt(1, 1);
stmt.setInt(2, 3);
stmt.setInt(3, 5);
int affected = stmt.executeUpdate();
if (affected == 1){
keys = stmt.getGeneratedKeys();
keys.next();
int newKey = keys.getInt(1);
orderBean.setOrderID(newKey);
}else{
System.out.println("An Error has ocurred while creating the Order.");
}
}catch (SQLException e){
System.err.println(e.getMessage());
}finally{
if (keys != null) keys.close();
}
And when I run the code I get this error:
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 'order (orderedBy, totalItems, totalPrice) VALUES (1, 3, 5)' at line 1
I'm not entirely sure why I get the error so if you know that would be great.

order is a reserved word, try
String sqlstatment = "INSERT INTO \"order\" (orderedBy, totalItems, totalPrice) "+
"VALUES (?, ?, ?);";

Your query contains a RESERVED KEYWORD order as your table name. MySQL documentation clearly suggests that use of such keywords should always be avoided, if they need to be used then it has to be with the use of backticks as shown below '`'.
Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.
If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.
Your query that gets assigned to a String in turn should be changed to the following to resolve this error!
"INSERT INTO \"order\" (orderedBy, totalItems, totalPrice) VALUES (?, ?, ?);"
The following is a documentation link to the reserved keywords for MySQL -> Documentation
Hope this helps!

Related

How to getGenerated id from parent table and insert into child table

try {
currentCon = ConnectionManager.getConnection();
psParent=currentCon.prepareStatement("insert into accommodation (type,name,price,description,username)values(?,?,?,?,?)", PreparedStatement.RETURN_GENERATED_KEYS);
psParent.setString(1,type);
psParent.setString(2,name);
psParent.setFloat(3,price);
psParent.setString(4,username);
psParent.executeUpdate();
accid= 0;
rs = psParent.getGeneratedKeys();
if (rs.next())
accid = rs.getInt(1);
rs.close();
psParent.close();
psChild=currentCon.prepareStatement("insert into room (accid, bed)values(?,?)");
psChild.setInt(1,accid);
psParent.setString(2,bed);
psChild.executeUpdate(); }
after I run this, I got this error message : failed: An Exception has occurred! java.sql.SQLRecoverableException: internal error
Is there's something wrong with the code? Thank you for your help
Your usage of getGenereatedKeys() actually looks correct to me for Oracle, but the problem is actually with your first insert statement. You have placeholders (and column names) for 5 columns, but you only bind 4 values. Try something like this:
String sql = "insert into accommodation (type, name, price, description, username) ";
sql += "VALUES (?, ?, ?, ?, ?)";
String generatedColumns[] = { "ID" };
psParent = currentCon.prepareStatement(sql, generatedColumns);
psParent.setString(1, type);
psParent.setString(2, name);
psParent.setFloat(3, price);
psParent.setString(4, description); // I ADDED THIS LINE
psParent.setString(5, username);
psParent.executeUpdate();
I am assuming that you have a variable containing a description to be inserted. If not, then remove description and its placeholder from the prepared statement entirely, or just insert null.

How to write "INSERT IF EXISTS UPDATE" in Oracle using JAVA

I have a ERROR_MSG table which stores error messages with some ids. I want to insert error message if id is not present in table and if its present update error message. Inserting using below java JDBC code.
ID ERROR_MSG
1 ERR1
2 ERR2
3 ERR3
This is my code:
insertQry = "SQL";
Connection con = null;
PreparedStatement stmt = null;
try {
con = getDataSource().getConnection();
stmt = con.prepareStatement(insertQry);
for(ListingAckNackData errorList: listOfListingERROR) {
stmt.setLong(1, eqGlobalData.getSrcMsgId());
stmt.setString(2, errorList.getGliId());
if (null != errorList.getListingRevisionNo()) {
stmt.setInt(3, errorList.getListingRevisionNo());
} else {
stmt.setNull(3, Types.NULL);
}
if (null != errorList.getErrorMessage()) {
stmt.setString(4, errorList.getErrorMessage());
} else {
stmt.setNull(4, Types.NULL);
}
stmt.addBatch();
}
stmt.executeBatch();
}
The simplest solution in JAVA is to check if the row exist.
You start by getting a row count for the specific id you want to insert/update
select count('a') as rowExist from table where id = ?
Then, based on the result, you can easily create your query
if(rowExist > 0){
query = "update ..";
else
query = "insert ...";
Note that the parameters are probably not in the same order as you expect, you need to create the insert in the correct order to have the id at the end (since update need a where clause)
insert into Table (name, birthday, id) values (?, ?, ?)
update Table set name = ?, birthday = ? where id = ?
It is possible to run a database statement as questioned. Simply use SQL command MERGE INTO... IF NOT MATCHED INSERT... IF MATCHED UPDATE ...
You will find an full example and documentation here.

JAVA mysql INSERT error

private final static String INSERT = "INSERT INTO electric_usage" +
"(objId, useTime, name, usage) " +
"VALUES (?, ?, ?, ?)";
public static boolean insertUsage(int index, Timestamp time, String name, double usage) {
Connection con = null;
try {
con = DBManager.getInstance().getConnection();
PreparedStatement stmt = con.prepareStatement(INSERT);
java.util.Date today = new java.util.Date();
stmt.setInt(1, index);
stmt.setTimestamp(2, time);
stmt.setString(3, name);
stmt.setDouble(4, usage);
stmt.addBatch();
stmt.executeBatch();
stmt.close();
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
DBManager.getInstance().close();
}
return true;
}
make INSERT query like this but this code occur syntax error
other load query is work fine only this INSERT quert occur error
im trying to INSERT query in console it occur same error
my query is wrong?
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 'usage) VALUES (192, '2015-09-10 13:55:57', 'test', 0.0045196452704869055)' at line 1
table is
objId(int length 8 not null)
useTime(timestamp length 0 not null)
name (varchar length 255 not null)
usage (double length 11 not null)
index is a reserved word so you should not use it to name a column. List of reserved words here: http://dev.mysql.com/doc/refman/5.6/en/keywords.html
That's because your column names index/usage are all MySQL Reserve words and so needs to be escaped using backtique like below
INSERT INTO electric_usage (`index`, `time`, `name`, `usage`)
Always avoid using table/column name as reserve word else you will have to suffer likewise. Use proper naming convention like prefix t_ for table names and c_ for column names.
index is reserved word in mysql you can't use mysql reserved words.when you write query in query browser than reserved words shows in blue. so please take care about this.if you write query in java coding directly you can't find these type of issues.

General error in JDBC(updating database)

private void sUpdateBtnActionPerformed(java.awt.event.ActionEvent evt) {
String query = "UPDATE Student SET lastname = ?, firstname = ?, course = ?, yearlvl = ?, username = ?, password = ?";
dbConn = DbConnection.dbConnect();
prepState = dbConn.prepareStatement(query);
prepState.setString(1, sLnTf.getText());
prepState.setString(2, sFnTf.getText());
prepState.setString(3, courseTf.getText());
prepState.setInt(4, Integer.parseInt(yearLvlTf.getText()));
prepState.setString(5, sUserTf.getText());
prepState.setString(6, sPassTf.getText());
prepState.executeUpdate();
}catch(Exception e){
appendEvent(sdf.format(new Date()) + " Error: " + e);
}
}
Method for connecting to the database:
import java.sql.*;
import javax.swing.*;
public class DbConnection {
Connection dbConn = null;
public static Connection dbConnect(){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection dbConn = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ=H:/Integ Ongoing Project/_Midterm Project/Server/src/database/Database.accdb");
return dbConn;
}catch(Exception e){
System.out.println(e.getMessage());
return null;
}
}
}
Password is a reserved word. If you must keep that as your field name, enclose it in brackets in your query to reduce the likelihood of confusing the database engine.
UPDATE Student
SET
lastname = ?,
firstname = ?,
course = ?,
yearlvl = ?,
username = ?,
[password] = ?
WHERE student_id = ?
Note I included a WHERE clause, as Stephen suggested, because it seems unlikely you would want those same field values applied to every row in the Student table. I used student_id as a placeholder name for the table's primary key ... the field which uniquely identifies each row. My intention is that you revise the WHERE clause to reference the primary key for the student whose record you want to alter.
If you're actually trying to add a new record, instead of update an existing record (or records), use an INSERT statement.
INSERT INTO Student (
lastname,
firstname,
course,
yearlvl,
username,
[password]
)
VALUES (
?,
?,
?,
?,
?,
?
)
And if you have autonumber as the data type of your primary key, the db engine will manage it for you.
I think that the problem is that your SQL statement is missing a WHERE clause. (I know that WHERE is optional in some dialects of SQL ... but a missing WHERE makes no sense to me here.)
The reason I think this is wrong is that even if the SQL dialect allows this, it is not clear which row of the table you are "setting". Even if the SQL engine can figure it out, a WHERE clause makes it a lot clearer. (And the fact that it "works" in the other case, doesn't mean that it is necessarily correct.)
Another thing that is potentially the cause of the problem is that "password" is a reserved word in some SQL dialects. Change the column name, or escape it.
Finally, the actual SQL error message should be in the exception stacktrace, or failing that in the log files. Those should be the first places to look if you are trying to find a problem in your database code. Look for the evidence ... rather than hoping someone else guess the right answer for you.

Error setting mysql primary key field with preparedStatement

This is my code for inserting a row. The columns are: primary id, name, and artist.
Am I passing the primary id correctly because it keeps on giving me an error? It is set to one and it increments every time a row is added.
try {
//Database
String query = "INSERT INTO lyrics1(lyrics1_id, name, artist) values(?, ?, ?)";
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(2, nameOfSong.getText()); // set input parameter 2
statement.setString(3, artist.getText());
statement.setLong(i, i);
ResultSet rs = statement.executeQuery("SELECT * FROM lyrics1");
while (rs.next()){
System.out.println(rs.getString(1));
}
statement.execute();
rs.close();
statement.close();
connection.close();
i++;
} catch (SQLException insertException) {
displaySQLError(insertException);
}
The error is:
SQLException: No value specified for parameter 1 SQLState: 07001 VendorError: 0
If your primary key is AUTO_INCREMENT, which it sounds like it is, you do not pass it with the INSERT statement, it is handled automatically for you. This would be what you want to do:
INSERT INTO lyrics1(name, artist)
VALUES(?, ?)
(This assumes your primary key isn't AUTO_INCREMENT and that you're passing it for a reason.)
I think you have a simple typo:
statement.setLong(i, i);
should probably be
statement.setLong(1, i);
// ^-- 1, not i
Being an old fuddy-duddy, I'd also probably move that statement above the other two so you're doing them in order.
If you have auto_increment in primary key:
String query = "INSERT INTO lyrics1(name, artist) values(?, ?)";
Don't forget to add the quotes when inserting a TEXT or VARCHAR value, like "INSERT INTO lyrics1(lyrics1_id, name, artist) VALUES ("id","name","artist").
Also, if the key is auto-incremental, do not pass it, the SQL will do it by itself. The query should then be "INSERT INTO lyrics1(name, artist) VALUES ("name","artist")."
As far as I know, you should have a ; in the string at the end like so:
String query = "INSERT INTO lyrics1(lyrics1_id, name, artist) values(?, ?, ?)";
however, it may work anyway.
You have a typo on the line you setting a value for primary key:
statement.setLong(i, i);
Here, did you see the first argument, it is i instead of 1. So it has to be changed to
statement.setLong(1, i);
But, if you ran the program for a second time, if the value of your i is initialized to a constant, you will get a primary key violation exception. Since, you are using MySQL, and if you used AUTO_INCREMENT for primary key column, then you can avoid that field in INSERT query. MySQL will automatically assign a value for the field. So you may use something like this:
INSERT INTO lyrics1(name, artist) values(?, ?)

Categories