I have an error doing a select in SQLITE - java

I'm trying to do this at onUpgrade() in my Android Java App:
try {
db.execSQL("SELECT fechacontrol from parametres", null);
} catch(Exception e) {
e.printStackTrace();
db.execSQL("ALTER TABLE parametres ADD COLUMN fechacontrol BIGINT");
}
My problem is, the column fechacontrol exists, but I always end up in the exception block, then the app crashes because of a duplicated column name.
What am I doing wrong?
Thanks you all.

execSQL(anything, null) will throw an IllegalArgumentException due to null bindargs. That's why you always end up in the catch. There is execSQL(String) overload for executing SQL without bindargs.
However, database upgrades should not be done like this. The schema version number is stored in the database file and you get it as a param in onUpgrade(). Use that information to deduce what needs to be updated.

Related

I have a SQl Insertion Error In My Library Mangement Project. I tried to Figure out myself but failedd many times.Help me out

String sql="insert into return (Student_ID,S_Name,F_Name,Course,Branch,Year,Semester,Book_ID,B_Name,Edition,Publisher,Price,Pages,Date_Of_Issue,Date_Of_Return) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
Error Says:
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 'return values-->
stm=con.prepareStatement(sql);
stm.setString(1,jTextField1.getText());
stm.setString(2,jTextField2.getText());
stm.setString(3,jTextField3.getText());
stm.setString(4,jTextField4.getText());
stm.setString(5,jTextField5.getText());
stm.setString(6,jTextField6.getText());
stm.setString(7,jTextField7.getText());
stm.setString(8,jTextField8.getText());
stm.setString(9,jTextField9.getText());
stm.setString(10,jTextField10.getText());
stm.setString(11,jTextField11.getText());
stm.setString(12,jTextField12.getText());
stm.setString(13,jTextField13.getText());
stm.setString(14,jTextField14.getText());
stm.setString(15, ((JTextField)jDateChooser1.getDateEditor().getUiComponent()).getText());
stm.execute();
JOptionPane.showMessageDialog(null,"Book Returned");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
First rename the "return" table in something else, it will prevent you about many error that can occur in the database or into java. Return is a reserved keyword in many cases.
In order to execute an insert you should use the stmt.executeUpdate() function.
Furthermore you should use named parameters to ensure each parameter is what it should be.

SQLite UNIQUE Exceptions handling JAVA

First of all I'm a begginer so please chill guyz. I'd like to create an app which allow us to get every one NOT UNIQUE row from first sqlite Table and place it to another table. So if the row already exist in the second table the program should increment index of row's ID. I mean sth like this e.g.
for(int i=0, i<10,i++){
query = "Select * from table where ID="+i;
executeQuery(query);
}
If the query cannot be executed I'm getting an exception like this one:
java.sql.SQLException :UNIQUE constraint failed: NewTableAUi.PHONE
I've got a little problem with catching an exception while the row I wanna insert is already exist. Thanks for all feedback!
So, if you are getting an exception, that means you need to handle it. Upon the query execution do something like this:
try {
//your query code
} catch (SQLException e) {
System.err.println("Exception Message");
}

hbm2ddl.auto is not creating schema automatically when set to create [duplicate]

I am getting below exception, when trying to insert a batch of rows to an existing table
ORA-00942: table or view does not exist
I can confirm that the table exists in db and I can insert data to that table using oracle
sql developer. But when I try to insert rows using preparedstatement in java, its throwing table does not exist error.
Please find the stack trace of error below
java.sql.SQLException: ORA-00942: table or view does not exist
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:289)
at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:573)
at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1889)
at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteFetch(TTC7Protocol.java:1093)
at oracle.jdbc.driver.OracleStatement.executeNonQuery(OracleStatement.java:2047)
at oracle.jdbc.driver.OracleStatement.doExecuteOther(OracleStatement.java:1940)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout>>(OracleStatement.java:2709)
at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:589)
at quotecopy.DbConnection.insertIntoDestinationDb(DbConnection.java:591)
at quotecopy.QuoteCopier.main(QuoteCopier.java:72)
Can anyone suggest the reasons for this error ?
Update : Issue solved
There was no problem with my database connection properties or with my table or view name. The solution to the problem was very strange. One of the columns that I was trying insert was of Clob type. As I had a lot of trouble handling clob data in oracle db before, gave a try by replacing the clob setter with a temporary string setter and the same code executed with out any problems and all the rows were correctly inserted!!!.
ie. peparedstatement.setClob(columnIndex, clob)
was replaced with
peparedstatement.setString(columnIndex, "String")
Why an error table or view does exist error was throws for error in inserting clob data. Could anyone of you please explain ?
Thanks a lot for your answers and comments.
Oracle will also report this error if the table exists, but you don't have any privileges on it. So if you are sure that the table is there, check the grants.
There seems to be some issue with setCLOB() that causes an ORA-00942 under some circumstances when the target table does exist and is correctly privileged. I'm having this exact issue now, I can make the ORA-00942 go away by simply not binding the CLOB into the same table.
I've tried setClob() with a java.sql.Clob and setCLOB() with an oracle.jdbc.CLOB but with the same result.
As you say, if you bind as a string the problem goes away - but this then limits your data size to 4k.
From testing it seems to be triggered when a transaction is open on the session prior to binding the CLOB. I'll feed back when I've solved this...checking Oracle support.
There was no problem with my database connection properties or with my table or view name. The solution to the problem was very strange. One of the columns that I was trying insert was of Clob type. As I had a lot of trouble handling clob data in oracle db before, gave a try by replacing the clob setter with a temporary string setter and the same code executed with out any problems and all the rows were correctly inserted!!!.
ie. peparedstatement.setClob(columnIndex, clob)
was replaced with
peparedstatement.setString(columnIndex, "String")
#unbeli is right. Not having appropriate grants on a table will result in this error. For what it's worth, I recently experienced this. I was experiencing the exact problem that you described, I could execute insert statements through sql developer but would fail when using hibernate. I finally realized that my code was doing more than the obvious insert. Inserting into other tables that did not have appropriate grants. Adjusting grant privileges solved this for me.
Note: Don't have reputation to comment, otherwise this may have been a comment.
We experienced this issue on a BLOB column. Just in case anyone else lands on this question when encountering this error, here is how we resolved the issue:
We started out with this:
preparedStatement.setBlob(parameterIndex, resultSet.getBlob(columnName)); break;
We resolved the issue by changing that line to this:
java.sql.Blob blob = resultSet.getBlob(columnName);
if (blob != null) {
java.io.InputStream blobData = blob.getBinaryStream();
preparedStatement.setBinaryStream(parameterIndex, blobData);
} else {
preparedStatement.setBinaryStream(parameterIndex, null);
}
I found how to solve this problem without using JDBC's setString() method which limits the data to 4K.
What you need to do is to use preparedStatement.setClob(int parameterIndex, Reader reader). At least this is what that worked for me. Thought Oracle drivers converts data to character stream to insert, seems like not. Or something specific causing an error.
Using a characterStream seems to work for me. I am reading tables from one db and writing to another one using jdbc. And i was getting table not found error just like it is mentioned above. So this is how i solved the problem:
case Types.CLOB: //Using a switch statement for all columns, this is for CLOB columns
Clob clobData = resultSet.getClob(columnIndex); // The source db
if (clobData != null) {
preparedStatement.setClob(columnIndex, clobData.getCharacterStream());
} else {
preparedStatement.setClob(columnIndex, clobData);
}
clobData = null;
return;
All good now.
Is your script providing the schema name, or do you rely on the user logged into the database to select the default schema?
It might be that you do not name the schema and that you perform your batch with a system user instead of the schema user resulting in the wrong execution context for a script that would work fine if executed by the user that has the target schema set as default schema. Your best action would be to include the schema name in the insert statements:
INSERT INTO myschema.mytable (mycolums) VALUES ('myvalue')
update: Do you try to bind the table name as bound value in your prepared statement? That won't work.
It works for me:
Clob clob1;
while (rs.next()) {
rs.setString(1, rs.getString("FIELD_1"));
clob1 = rs.getClob("CLOB1");
if (clob1 != null) {
sta.setClob(2, clob1.getCharacterStream());
} else {
sta.setClob(2, clob1);
}
clob1 = null;
sta.setString(3, rs.getString("FIELD_3"));
}
Is it possible that you are doing INSERT for VARCHAR but doing an INSERT then an UPDATE for CLOB?
If so, you'll need to grant UPDATE permissions to the table in addition to INSERT.
See https://stackoverflow.com/a/64352414/1089967
Here I got the solution for the question. The problem is on glass fish if you are using it. When you create JNDI name make sure pool name is correct and pool name is the name of connection pool name that you are created.

How to solve when existing primary key in MS SQL kills java program (because of SQL Exception)

we try to insert Primary Keys (Strings) in our MS SQL Database, sometimes the program will try to insert a PrimaryKey although this key is already existing in the db. Then the Java program will be stopped because of the exception which the MSSQL Server throws. How is it possible not to listen to this Exception in Java OR to disable this Message from the MSSQL Server?
We could check that in java before we try to insert but it would be better for the performance not to check every time, just throwing away the error-message would be fine!
Suppress the exception with a try statement:
try {
//.....code that inserts
}
catch (SQLException sqle) {
//ignore or do something else here
}

Detecting when inserting duplicate rows in Java/MyBATIS

I am currently using MyBATIS in my project.
I sometimes need to run an INSERT query but ignore if the row I'm trying to insert is already present on DB, but instead handle other SQL errors.
How can I find that the SQLException is related to primary key violation?
Something like
try {
sqlMap.insert(query, params);
} catch (DuplicateKeyException ex) {
//Do nothing, it's OK for mew
} catch (SQLException ex) {
throw ex;
}
I suppose that specific exception doesn't really exist...
SQL isn't my strong point, but you could look into the Error Code and SQL State codes contained within the SQLException that would be thrown. Those may offer more insight into why the query failed.

Categories