in my application I'm trying to insert a query into an oracle database using jdbc. I create this table:
create table TMP
(
SYNC NUMBER,
USER VARCHAR2(50),
DAT DATE
)
And I use this code to insert an entry:
PreparedStatement stat=null;
try {
dbStatement = dbConnection.createStatement();
String sql = "INSERT INTO TMP (USER, DAT) Values (?,?);";
for (ReplicationHistoryDetailVO tmpEntry : entry) {
if (tmpEntry.getSyncPhase() == REPLICATION_PHASE.DOWNLOAD) {
stat=dbConnection.prepareStatement(sql);
stat.setString(1, "David");
stat.setDate(2, new Date(tmpEntry.getFinishTime()));
stat.executeUpdate();
}
}
From this code I have the following error:
Error updating database java.sql.SQLSyntaxErrorException: ORA-00911
The connection is ok. I must to write only two values, because the first value is an autoincremental key and I don't set this. Any ideas?
Try "INSERT INTO TMP (USER, DAT) Values (?,?)" without the ; at the end.
ORA-00911 is a common error for common syntax mistakes.
Related
I am trying to connect my java project with database in netbeans. I have a table named task_table and i'm trying to add some values on that table.
Here is my code
Connection con1;
PreparedStatement insert;
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String name1= addtaskname.getText();
String name2= addtaskdate.getText();
String name3= addtasktime.getText();
try {
Class.forName("com.mysql.jdbc.Driver");
con1 = DriverManager.getConnection("jdbc:mysql://localhost/jesin_virtual","root","");
insert = con1.prepareStatement("insert into task_table(Task Name,Task Date,Task Time) values (?,?,?)");
insert.setString(1, name1);
insert.setString(2,name2 );
insert.setString(3,name3);
insert.executeUpdate();
JOptionPane.showMessageDialog(this, "Task Added sucessfully");
and i got this exception:
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
The problem is here:
insert into task_table(Task Name,Task Date,Task Time) values (?,?,?)
^ ^ ^
If the column names really contain blanks, then you need backticks around the names (`Task Name`), else change the names to what they really are (Task_Name maybe?).
Please correct SQL query inside as below...
if in your database column names contains space so please use below query
"insert into task_table("Task Name","Task Date","Task Time") values (?,?,?)"
if in your database column names contains _ so please use below query
"insert into task_table(Task_Name,Task_Date,Task_Time) values (?,?,?)"
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.
I am trying to access a database to then insert new data, but the code below gives me this output:
Opened database successfully
java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database ()
The database is created in a different class, I still get this error whether the database has already been created or not.
What would be causing this error?
Statement stmt = null;
Connection c = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:src/test.db");
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "INSERT INTO table_one (id, name) VALUES (Null, 'Hayley');";
stmt.executeUpdate(sql);
System.out.println("Inserted records");
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Table created sucessfully");
How about not inserting the null value in the id column. It is of no use to insert null value. It might have generated the sql exception. Try INSERT INTO table_one (name) VALUES ('Hayley');.
I would suggest to use PreparedStatement instead of Statement because of the threat of SQL injection.
Sometimes, the particular sql exception can occur if the database name is not given. Have you tried writing the database name like INSERT INTO database_name.table_one (name) VALUES ('Hayley');.
My source code has the following structure:
SourceFolder
AddProduct.jsp
Source Packages
-Controller(Servlets)
SaveProduct.java
-Model(Db Operations)
ProductDbOperations.java
I am inserting a new product into the product table and at the same time I am inserting an entry into product_collection table (product_id | collection_id).
To insert an entry into the product_collection table i need to get generated id from product table. After that a new entry is inserted into the product_collection table.
Also, I am not using any Framework and am using Netbeans 7.3.
Problem:
A new entry is inserted into the product table with this piece of code
IN: ProductDbOperations.java
try
{
this.initConnection(); // Db connection
pst = cn.prepareStatement("INSERT INTO product values('"+name+"', "+quantity+", "+price+")");
rs = pst.executeUpdate();
}
catch(SQLException ex)
{
}
I Also used the solution at following link which doesn't works for me.
I didn't got any SQL exception
How to get the insert ID in JDBC?
so help me find out why this code not working for me .
Thanks a million.
Not all drivers support the version of getGeneratedKeys() as shown in the linked answer. But when preparing the statement, you can also pass the list of columns that should be returned instead of the "flag" Statement.RETURN_GENERATED_KEYS (and passing the column names works more reliably in my experience)
Additionally: as javaBeginner pointed out correctly, your usage of a prepared statement is wrong. The way you do it, will still leave you wide open to SQL injection.
// run the INSERT
String sql = "INSERT INTO product values(?,?,?)";
pst = cn.prepareStatement(sql, new String[] {"PRODUCT_ID"} );
pst.setString(1, name);
pst.setInt(2, quantity);
pst.setInt(3, price);
pst.executeUpdate();
// now get the ID:
ResultSet rs = pst.getGeneratedKeys();
if (rs.next()) {
long productId = rs.getLong(1);
}
Note that the column name passed to the call is case-sensitive. For Oracle the column names are usually uppercase. If you are using e.g. Postgres you would most probably need to pass new String[] {"product_id"}
The way you are using is not the proper way of using preparedstatement
use the following way
pst = cn.prepareStatement("INSERT INTO product values(?,?,?)");
pst.setString(1,name);
pst.setInt(2,quantity);
pst.setInt(3,price);
pst.executeUpdate();
Yes there is a way to retrieve the key inserted by SQL. You can do it by:
Using Statement.RETURN_GENERATED_KEYS in your previous insert and get the key which can be used in further insert
e.g:
String query = "INSERT INTO Table (Col2, Col3) VALUES ('S', 50)";
Statement stmt = con.createStatement();
int count = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
Here is the code that works:
Connection c = ds.getConnection();
c.setAutoCommit(false);
PreparedStatement stmt = c.prepareStatement("INSERT INTO items (name, description) VALUES(?, ?)");
while (!(items = bus.take()).isEmpty()) {
for (Item item : items) {
stmt.setString(1, item.name);
stmt.setString(2, item.description);
stmt.addBatch();
}
stmt.executeBatch();
c.commit();
}
But now I need to populate another table where id is a foreign key.
If I use INSERT with RETURNING id then executeBatch fails with "A result was returned when none was expected" error.
I see several ways to solve this
Do individual insert rather than the batch insert.
Replace serial id with client generated guid.
Use some kind of a stored procedure to perform the batch insert and return a list of ids.
Of the three methods that I see the last one seems to preserve both the efficiency of batch insert and return the ids, but it is also the most complex for me as I have never written stored procedures.
Is there a better way to batch insert and get the IDs? I have no problem using postgresql specific API rather than jdbc.
If not, could any one sketch such a stored procedure?
Here is the table schema:
CREATE UNLOGGED TABLE items
(
id serial,
name character varying(1000),
description character varying(10000)
)
WITH (
OIDS=FALSE
);
Something like this should work:
// tell the driver you want the generated keys
stmt = c.prepareStatement("INSERT ... ", Statement.RETURN_GENERATED_KEYS);
stmt.executeBatch();
// now retrieve the generated keys
ResultSet rs = stmt.getGeneratedKeys();
while (rs.next()) {
int id = rs.getInt(1);
.. save the id somewhere or update the items list
}
I think (I am not sure!) that the keys are returned in the order they were generated. So the first row from the ResultSet should map to the first "item" from the list you are processing. But do verify that!
Edit
If that doesn't work, try specifying the actual columns for which the values are generated:
stmt = c.prepareStatement("INSERT ... ", new String[] {"id"});