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");
}
Related
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.
I am building a java project. I want to check if a primary key already exist in my table. For example I have the below code:
private void AddProductActionPerformed(java.awt.event.ActionEvent evt)
{
String query="INSERT INTO Products(Pro_Id ,Pro_Name,Pro_Price,Pro_Quantity,Pro_Supplier_id)VALUES ('"+Pro_Id.getText()+" ','"+Pro_Name.getText()+" ','"+Pro_Price.getText()+" ','"+Pro_Quantity.getText()+" ','"+Pro_Supplier_id.getText()+" ') ";
executeSQLQuery(query,"Inserted");
}
How can I get a message that tells me to change the entry of primary key if it already exists?
You can put your code inside try catch block.
Inside catch block check for SQLException
public static final int MYSQL_DUPLICATE_PK = 1062; // Replace 1062 with exception no. you are getting in case it is different for different database
try{
String query="INSERT INTO Products(Pro_Id ,Pro_Name,Pro_Price,Pro_Quantity,Pro_Supplier_id)VALUES ('"+Pro_Id.getText()+" ','"+Pro_Name.getText()+" ','"+Pro_Price.getText()+" ','"+Pro_Quantity.getText()+" ','"+Pro_Supplier_id.getText()+" ') ";
executeSQLQuery(query,"Inserted");
} catch(SQLException e){
if(e.getErrorCode() == MYSQL_DUPLICATE_PK ){
System.out.println("Primary key already used");
}
}
How can I get a message that tells me to change the entry of primary
key if it already exists?
Make sure you have marked Pro_Id as PRIMARY KEY while defining your table structure which will make sure this behavior and if you try to insert duplicate value it will throw error.
You would get an error if you try your code and the key already exists. Depending on this error for your program to work during a normal flow is not a good idea, as exceptions are always expensive in terms of performance. What you should do is check if the primary key exists already before trying to insert. This can be done by executing a SELECT query.
SELECT 1 FROM Products WHERE Pro_Id = :yourDesiredPk;
When the result of the query is not empty it would mean that it already exists.
A better idea is to consider using a sequence and using the next value aka auto increment, check it out on google (What is a sequence (Database)? When would we need it?). That way you can avoid having duplicate PK problems. But maybe your PK is not a number and has some business logic behind it, in that case a sequence is not an option.
Before insert record do one thing do count(*) and if count is 0 then and then insert the same otherwise show popup for duplicate query.
I'm working on a project in Java, where, I have to make modifications in my SQLite Database.
I connected to it and is working pretty fine, except for this weird error.
s.executeUpdate("INSERT INTO STUDENTS VALUES('S0',11)");
...
//many statements... including queries
...
String c2="INSERT INTO STUDENTS VALUES ('S1', 2)";
s.executeUpdate(c2);
s.executeUpdate("DROP TABLE STUDENTS");
The statements s.executeUpdate("INSERT INTO STUDENTS VALUES('S0',11)"); and s.executeUpdate(c2); run perfectly and insert rows into the database. But when it comes to the statement below, I'm getting the weird Database Locked error.
When I changed the query to another, it also worked pretty fine. The error comes when it reaches the ending statement. More precisely, all the queries written above, i.e., the first statement of the code here work pretty fine.
Please help me to find the bug.
I guess that the "s" variable is a Statement. Try closing the resources after you execute:
PreparedStatement updateStatement = connection.prepareStatement("INSERT INTO STUDENTS VALUES ('S1', 2)");
try {
updateStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
updateStatement.close();
}
Do this after every call to the database.
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.
I have 2 tables named T1 and T2. Where T1 is parent and T2 is child.
The scenario is, I started a jdbc transaction and then insert a row in T1 and then try to insert a row in T2. Inserting row in T2 gies me "Integrity Constraint-Parent key not found" exception.
How i handle this scenario ?
Connection con;
try{
con = ConnectionPool.getConnection();
con.setAutoCommit(false);
int T1Id = getNewId("T1"); // from sequence;
int T2Id = getNewId("T2"); // from sequence;
Insert in to table T1(t1Id,tName) values (T1Id,'A')
Insert in to table T2(t2Id, t1Id,tName) values (T2Id,T1Id,'A')//Here, Exception raises
con.commit();
}catch(Exception e){
try {con.rollback();} catch (SQLException e) {}
}finally{
try {con.setAutoCommit(true);} catch (SQLException e) {}
ConnectionPool.returnConnection(con);
}
Using JDBC API, struts1.2, Oracle10 G Database
You are probably doing something wrong. If both inserts are within the same transaction what you've just mentioned can't happen. Please share some code and more information (DB server, table structures) to see if we can help you.
You need a three step process:
INSERT row into parent
SELECT the generated key from the parent
Use the generated key and the child information to INSERT into the child
It should be a single unit of work, so make it transactional.
It's impossible to tell from your pseudo code. It'd also be helpful to know whether or not you're using auto generated keys.
I'm guessing that the primary key you're assuming for T1 doesn't actually appear. If T2 says the foreign key cannot be null or is required, and it doesn't appear in T1, then the RDBMS system should complain and throw an exception.