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');.
Related
Hi I have a problem with my syntax in my java code. I have a tableview which gets its data from a SQL database. I have created 3 tables in the database book, customer, order. When I click a button I want to take the selected books and add them to the order table.
Here is the code from the main program (calling the method from db):
if(table.getSelectionModel().getSelectedItems().iterator().hasNext()) {
db.insertOrder(new Bestellung(customerid,table.getSelectionModel().getSelectedItems().iterator().next()));
The table book is fixed. Just the two other tables customer,order are dynamic.
The problem:
I create the values in the order table like this
String ct = "CREATE TABLE Order (" + "Order_Id integer generated always as identity, " + "CUSTOMER_ID BIGINT" + "ISBN, CHAR(13) " + "PRIMARY KEY(Order_Id))";
and so on...
I insert into order table like this. (Here is the syntax problem in the String i That's the position where the compiler says it doesn't work..)
String i = "INSERT INTO ORDER(CUSTOMER_ID,ISBN), VALUES(?,?)";
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DriverManager.getConnection(connString);
stmt = conn.prepareStatement(i);
conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
stmt.setLong(1, order.getCustomerId());
stmt.setString(2, order.getBuch().getISBN());
stmt.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
finally {
try {
if (stmt != null)
stmt.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
and here is the syntax error which I got
Syntax error: Encountered "ORDER" at line 1, column 13.
So how do I have to correct my syntax in the string i? Does anyone have any ideas?
INSERT INTO ORDER(CUSTOMER_ID,ISBN), VALUES(?,?)
^
The comma is superfluous. Also, in your CREATE TABLE
... + "ISBN, CHAR(13) " + ...
^
This comma is also extraneous.
If you want to use reserved words/keywords as Table name, you should:
MySQL: use ' , like : select * from 'Order'
Oracle, PostgreSQL: use " , like : select * from "Order"
But it is bad practice, try to change your table name.
You have another Error that answered by #Jim Garrison.
In my Struts2 Java web application users are allowed to query the database. As an example, the user needs to get the employee details whose first name is equal to 'Charles'. Then s/he can select the report columns and criteria (firstname='Charles').
Once the user gives above inputs it need to save the relevant SQL query into the database.
e.g. SQL -> SELECT * FROM employee WHERE firstname='Charles'
Here is what I am trying in my action class.
try {
connection = DriverManager.getConnection(
SelectAction.getDatabase(), SelectAction.getUser(),
SelectAction.getPassword());
if (connection != null) {
System.out.println("Database connection established!");
stmt = connection.createStatement();
String sql = "INSERT INTO reports (report_id, sql) values ('" + reportId + "', '" + sqlQ + "');";
System.out.println("sql--->" + sql);
// Executing query
stmt.executeQuery(sql);
return SUCCESS;
} else {
System.out.println("----Failed to make connection!");
return ERROR;
}
} catch (SQLException e) {
System.out.println("Connection Failed!!");
e.printStackTrace();
return SUCCESS;
}
This is my insert query.
INSERT INTO reports (report_id, sql) values ('mynewreport', 'SELECT * FROM employee WHERE firstname='Charles'');
I am getting following error in my console.
ERROR: syntax error at or near "Charles"
I think here I am using a String so that the problem is with quotes('). I am using postgreSQL as database.
Any suggestions to solve this issue ?
Never use string concatenation of user supplied values to build a SQL statement.
Never use string concatenation of any non-integer values to build a SQL statement.
You will leave yourself open to SQL Injection attacks and/or SQL statement errors.
Hackers will love you for allowing them to steal all your data, and the nefarious ones will corrupt or delete all your data, while laughing maniacally at you on their way to the bank.
Use PreparedStatement and parameter markers.
String sql = "INSERT INTO reports (report_id, sql) values (?, ?)";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, reportId);
stmt.setString(2, sqlQ);
stmt.executeUpdate();
}
Is this query possible on java?
"BEGIN;"
+ "INSERT INTO product(code, name, description, category_id) "
+ "VALUES(?,?,?,?);"
+ "INSERT INTO inventory_item(quantity, price, product_id) "
+ "VALUES(?,?,LAST_INSERT_ID());"
+ "COMMIT;";
I used it on a PreparedStatement and it really eating my time just to figure out the error my dbUnit said there is an error on the statement
com.example.dao.exception.DataAccessException:
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 'INSERT INTO product(code, name, description,
category_id) VALUES('00003','lemon ' at line 1
at
com.example.dao.InventoryDaoImpl.addInventoryItem(InventoryDaoImpl.java:126)
I can't print the PreparedStatement on the console I tried
PreparedStatement statement =
connection.prepareStatement( FIND_INVENTORY_ITEM_BY_PRODUCT_CODE_QUERY );
System.out.print( statement );
Can you guys give me a hand figure out the error?
May not be the way, but this has always worked for me:
List<String> sqlStatements = new ArrayList<String>();
// stuff your statements into this list
// (I'm often reading them from some file. The file often
// contains blank lines, comments and semicolons, which I
// strip out.)
Statement stmt = null;
try {
dbConn.setAutoCommit(false);
stmt = dbConn.prepareStatement();
for ( String sql : sqlStatements ) {
logger.debug("\t"+sql);
stmt.addBatch(sql);
}
stmt.executeBatch();
dbConn.commit();
} catch ( Exception e ) {
// handle exceptions
} finally {
// close statement
}
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.
I am trying to insert an email ID to a table in my SQLite3 Database. In my case it successfully creates the table but gives an error while inserting a record in it - "near "#gmail": syntax error". How can i resolve this ? Here is the code -
public void insertData(String emailId, double gtse, long receivedDate) throws ClassNotFoundException, SQLException{
Class.forName("org.sqlite.JDBC");
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection("jdbc:sqlite:testdb.sqlite");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
ResultSet result = statement.executeQuery("SELECT name FROM sqlite_master WHERE type='table' AND name='T1'");
if(!result.next()){
statement.executeUpdate("create table T1 (email TEXT, gtse REAL, receiveddate DATE)");
statement.executeUpdate("insert into T1 values(" + emailId + ", "+ gtse +", "+ receivedDate +")");
}
else{
}
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}
catch(SQLException e)
{
// connection close failed.
System.err.println(e);
}
}
}
Your core error is that for the insert query you are not enclosing the values to be inserted, in quotes. Your query, after construction, looks something like this:
insert into T1 values(whatever#gmail.com, emailtexthere, 04-07-2013)
When it should be something like this:
insert into T1 values('whatever#gmail.com', 'emailtexthere', '04-07-2013')
The SQL parser chokes while trying to parse your current query, because the syntax is incorrect. The solution to this problem is not simply to enclose the values in quotes though, but rather to use prepared statements. This is because the way you are constructing your query right now is vulnerable to SQL injection attacks. Here is an example of using a prepared statement:
PreparedStatement pStmt = conn.prepareStatement(
"INSERT INTO T1 VALUES(?, ?, ?)");
pStmt.setString(1, emailId);
pStmt.setString(2, gtse);
pStmt.setDate(3, receivedDate);
pStmt.execute();