Java SQLite Update query not working [duplicate] - java

This question already has answers here:
Not equal <> != operator on NULL
(10 answers)
Closed 8 years ago.
After hours (basically the entire day) of wriggling around, wrapping my throughts and whatnot, I am baffled as to why my UPDATE statement in SQLite does not want to work.
It concerns the following queries:
sql.Update("UPDATE SAVEGAME SET _id = \"save\" WHERE _id = null");
sql.Update("UPDATE SAVEGAME SET WORLD_ONE = \""+finishedLevels+"\" WHERE _id = 'save'");
I've also tried
sql.Update("UPDATE SAVEGAME SET _id = 'save' WHERE _id = null");
sql.Update("UPDATE SAVEGAME SET WORLD_ONE = '"+finishedLevels+"' WHERE _id = 'save'");
but to no avail.
The function I'm calling is this:
public void Update(String query){
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(query);
db.close();
}
Debugging clearly shows that the functions is being called and stepped through but refuses to work.
Any other SQL function I call (e.g. to create new tables etc.) all have their db.close() call present.
I've also tried looking at a different project where the UDPATE statement does work, but I can't find any differences (instance of my SQLLib class, function calls are the same, etc.)
It would seem so simple to call an UPDATE statement, but it has a fault somewhere.
Where is this fault? Because I'm at a total loss now.
-Zubaja

You are using = null when you need to use is null:
Change:
sql.Update("UPDATE SAVEGAME SET _id = \"save\" WHERE _id = null");
To this:
sql.Update("UPDATE SAVEGAME SET _id = \"save\" WHERE _id is null");
^^^^
Also, you may want to check how you are creating your SQL strings - inserting variables like that leaves your code prone to SQL Injection attacks.

Related

SQLite query returns only one row JDBC JAVA database

I have read the previous questions but none of them seem to match my problem although they might seem similar at first. :/_
So, I am working on a local database on Java(JDBC). When I press a button I should be getting the result of a "SELECT" query. So far so good, but for some reason which my beginner brain does not understand I keep getting only one row from the query. I have even run the same exact query on "DB Browser for SQLite" and it returns the correct result (1+ rows) .
So this is the method I am using to get the result of the query:
public ResultSet returnBill(int no) throws SQLException{
String sql = "SELECT * FROM billList WHERE no = " + no + " ;";
ResultSet thisSet = stmt.executeQuery(sql); // stmt is a 'Statement' type variable
return thisSet;
}
The method does not crash but it only returns the very first row of a query which should return more than 2 ( while (thisSet.next()) RUNS ONCE). I run other "SELECT" queries on the program which are supposed to return more than one rows and they all work fine so it's not a matter of not being able to start/close the connection etc.
Below is the method being used:
int number = table.getModel().getValueAt(rows, 0);
ResultSet thisSet = db.returnBill(number);
while (thisSet.next()){
String name = thisSet.getString("name");
int quantity = thisSet.getInt("quantity");
// do something with the returned data
}
So I get this magical number from a table (of course I made sure it's not 0, -1 etc.) and I run a query using that number. You could think of the structure of the table consisting of columns :
number | name | quantity |
where 'number' is nonzero.
I understand that probably using this method to run a query on a DB might not be safe or might post security threats but it's not the case right now. I have been working on this project for quite a long time already and I have been through many silly mistakes and I think this is yet one of them. Any help is APPRECIATED ! :D
So yes, it was a silly mistake as I expected.
So I had previously initiated a variable
Database db = new Database();
which opened the database for 2 queries (the SELECT query and an UPDATE query on another table as shown) which would then be closed at the end of the following code.
When I removed this UPDATE query however the loop executed the correct amount of times. So it seems like the SQLite JDBC is somehow prone to running a SELECT and UPDATE query on the same Statement (as far as my super mega* brain perceives it.)
So I created 2 connections at the very beginning and closed them at the end using one of them for the SELECT and the other one for the UPDATE query:
Database db = new Database(); // open database
Database db2 = new Database(); // open another creepy one :/
int number = table.getModel().getValueAt(rows, 0);
ResultSet thisSet = db.returnBill(number);
while (thisSet.next()){
String name = thisSet.getString("name");
int quantity = thisSet.getInt("quantity");
// do something with the returned data
// --------> STUPIDO <----------
//** Now executing an UPDATE query on db2 :
// ex.: UPDATE anotherTable SET amount = (current+ "+ quantity+") WHERE name= '" + name+ "' ;";
}
db.closeConn(); // close db ++
db2.closeConn(); // closes db 2
I don't know if this is the best approach but it solved my problem, so I'm leaving it so probably it could help. Any suggestions though would be welcomed :D

parameterized insert/update in sql

I am trying to insert into a db that I have, and I'd like to do so through parameters. I am connecting to a postgres db using java.
I can connect to the db just fine. I know that because I have various operations that I am using that are already working were I can see, and update existing rows in my db. I am having trouble with INSERT.
I have the following:
private String _update_rentals = "INSERT into rentals (cid, mid) values (?,?)";
private PreparedStatement _update_rentals_statement;
private String _update_movie_status = "UPDATE Movie SET checkedout = true WHERE mid = ?";
private PreparedStatement _update_movie_status_statement;
And I initialize them:
_update_movie_status_statement = _customer_db.prepareStatement(_update_movie_status);
_update_rentals_statement = _customer_db.prepareStatement(_update_rentals);
And
while (movieAvail.next()){
System.out.println(movieAvail.getBoolean(1));
if (movieAvail.getBoolean(1) == false){
//Do chekcout
_update_rentals_statement.clearParameters();
_update_rentals_statement.setInt(1, cid);
_update_rentals_statement.setInt(2, mid);
_update_rentals_statement.executeQuery();
_update_movie_status_statement.clearParameters();
_update_movie_status_statement.setInt(1, mid);
_update_movie_status_statement.executeQuery();
System.out.println("Enjoy your movie!");
}
}
I am getting an error with both of the executeQuery() calls. For some reason I am getting the following error with both:
Exception in thread "main" org.postgresql.util.PSQLException: No results were returned by the query.
I looked at other posts, and I believed that I was following syntax for both insert/ update correctly, so maybe I am overlooking some aspect of this.
This is all part of a larger code base, so I did not want to include the methods these pieces of code are in. But these are the isolated instances which play a part with this code.
In general, when you execute a query, you are willing to retrieve some kind of information from the database. This is usually the case when you are executing SELECT queries. However, with INSERT and UPDATE statements, you are not querying the database, you are simply executing an update or inserting new rows. In the documentation of PreparedStatement you can see in which cases an exception is being thrown when you try to call executeQuery:
Throws: SQLException - if a database access error occurs; this method
is called on a closed PreparedStatement or the SQL statement does not
return a ResultSet object
So in your case the problem is that your statements do not return a ResultSet. You should use execute or executeUpdate instead. The former simply executes the update, while the latter does the same, but also returns the number of affected rows.
I think the main issue is that you are calling executeQuery(), which expects a result to be returned, but Insert/Update are not queries and don't return a result. Try just calling execute().

How to get the ID of auto generated id from the Database [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to get the insert ID in JDBC?
I have the following tables:
customer(cid, ...)
book(cid, rid)
reservation(rid, ...)
I want to add a reservation in its table then I want to add in a relationship in book between customer and reservation.
How can I know rid while it is auto generated, and when I execute the query I did get a ResultSet returned?
The rid is auto generated form Oracle using a sequence and a trigger.
Refer to your question I believe you are using statements. In this case, you can use Statement.RETURN_GENERATED_KEYS. Also please consider this link as below solution can have conficts for Oracle database.
Here is small example:
Connection connection = database.getConnection();
PreparedStatement statement = connection.prepareStatement(myQuery, Statement.RETURN_GENERATED_KEYS);
int count = statement.executeUpdate();
if(count <= 0){
//value not inserted
}
ResultSet results = statement.getGeneratedKeys();
if(results.next){
System.out.println(generatedKeys.getLong(1));
}
in case of you are using ORM:
If you are using JPA entitiyManager.merge(entity); (or update) should return persisted instance with ID.
Quite similar with hibernate session.merge(entity); (or update)
Dunno how it is with java/jsp, but if it's a relational DB, you'd have to use a set of queries - i.e. get the one id you do know (cid) and then get the rid from the book table. There's no other way I know of.
Hope that helps.

Oracle DB Query Runs in sqlDev but not in Java Program

I have been messing with Oracle DB queries that run from my JAVA app. I can successfully get them all to run in SQL Developer. But when I am trying to execute them from my JAVA app I usually get UpdatadbleResultSet Error/Exception on certain queries.
Also, sometimes I receive, ExhaustedResultset. As I mention at the bottom I will re work the question to break it down(When I get a chance). I keep editing and pretty soon it'll be a book.
Why is this? I cannot seem to pinpoint the problem.
Some queries run successfully such as:
SELECT table_name
FROM all_tables
SELECT column_name, data_length
FROM all_tab_columns
WHERE table_name = 'mytable'
But when I try and run something like
SELECT length(<myColumnName>)
FROM mytable
I get the updateableResultSetError
I am running my queries as methods called on button clicks (example below).
static void testQuery() {
String query = "SELECT blah from blah"
String length;
ResultSet rs = db.runQuery(query);
Length = rs.getString("length(myCol)")
System.out.println(length);
}
I have also tried while rs.next()
I can only think that for some reason I am unable to get into each table and I can only pull the "bigger" picture.
EDIT: Explained DB Connection
I am connecting using some other jarfiles that have been added to my project.
private static IDriver driver = null;
private static Database db = null;
I then pass in all my connection credentials in a separate method.
private void connectDB(){
driver = new OracleDriver();
db = new Database(driver)
driver.getPassword;
driver.getetc;
driver.getEtc;
}
EDIT:
When I getstacktrace all I am returning is.
Ljava.lang.StatckTraceElement;(assortment of random characters).
I may not be getting stack traces right so someone can fill me in. After all I am offering a bounty.
Also I will edit this question and break it down again when I have the time.
Your problem is that you're trying to update a query that can't be updated, hence the updateable result error. It seems that whoever is creating your database connection or executing your query is creating an updatable result set.
You can't use certain types of select in an updatable result set: you can't use aggregated functions (such as length, min, max), you can't use select * etc.)
For the full list see Result Set Limitations and Downgrade Rules
Try retrieving the value in your select statement via the columnIndex instead of the column name and see if that makes a difference.
Currently, its hard to tell what your db.runQuery() does since that code is not posted.
String query = "SELECT length(myCol) FROM myTable";
String length;
ResultSet rs = db.runQuery(query);
while (rs.next()) {
length = rs.getString(1);
System.out.println(length);
}
I've got an inkling what may be happening here (which would explain why some queries work, and some don't). Accoring to the jdbc ResultSet javadocs, when using the getString() method of the result set, the column label.
the label for the column specified with the SQL AS clause.
If the SQL AS clause was not specified, then the label is the name of the column
As "length(myCol)" is neither a label nor a column name, it may be that it fell over because of that (but without stacktrace it is difficult to say what your problem actually is).
Try
String query = "SELECT length(myCol) AS myCol_len FROM myTable"
ResultSet rs = db.runQuery(query);
String length = rs.getString("myCol_len");
Though are you sure, you didn't want:
int length = rs.getInt("myCol_len");
Alternatively (as written by Kal), you can use the column index to get the data from the result set, which oblivates the need for a SQL AS label:
String query = "SELECT length(myCol) FROM myTable"
ResultSet rs = db.runQuery(query);
String length = rs.getString(1);

Getting the last inserted record id of a database table in java? [duplicate]

This question already has answers here:
How to get the insert ID in JDBC?
(14 answers)
Closed 7 years ago.
I have a database table A which stores records, A has a primary key (recordid) with auto_increment, each time i insert a record in to A, i get the inserted recordid and store it in another masterTable.
I am using a select statement as soon i do an insert into A to get the recordid like this:
select recordid from A order by recordid DESC LIMIT 1;
But i ran into a problem today, where in two records were inserted(by different threads) at the same time and i ended up storing wrong recordid in the master id( the same recordid for both the txns)
I heard about Statement.getGeneratedKeys(), I would like to know if that really helps resolve the issue. Or what is the best way to handle this.
You can use the getGeneratedKeys method. This forum post will help.
May I also recommend that you use an ORM tool like Hibernate. In Hibernate you would do something like this:
myTable = new myTable();
myTable.prop1 = prop1;
myTable.prop2 = prop2;
int id = session.save(myTable);
Hibernate will issue the appropriate SQL commands (depending on the database selected) and return you the auto-generated id.
The MySQL JDBC driver does support the getGeneratedKey() method. Have a look at the section 20.3.5.1.4. Retrieving AUTO_INCREMENT Column Values of the MySQL manual where:
we demonstrates the use of the new JDBC-3.0 method getGeneratedKeys() which is now the preferred method to use if you need to retrieve AUTO_INCREMENT keys.
In databases that don't support generatedKeys you may be able to get the ID into a return parameter. Oracle for example provides the RETURNING xxx INTO ? syntax where xxx is your column name.

Categories