How to get numbers of affected rows in sqlite - java

Hi I have query like this:
PreparedStatement prep = conn.prepareStatement("update Products set amount=? where codebar=? and price=?;");
Is any way in sqlite to get number of affected rows? And how can I get it?
Thx

Try this -
PreparedStatement prest = con.prepareStatement("update Products set amount=? where codebar=? and price=?");
prest.setDouble(1, 10.00);
prest.setInt(2, 1);
prest.setDouble(1, 50.00);
int rowCount = prest.executeUpdate();
The return value for executeUpdate() is an int value that indicates how many rows of a table were updated.
Check following link for more info -
http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html

According to Java documentation, you can use executeUpdate() method to get count of updated rows.

Can't you just run a select statement before the update to count how many rows match the criteria?

Related

Java sql - delete half rows in DB table

I want to delete a bunch of rows from a DB file that I have in a folder. Connecting and counting the amount of rows in the db file works but when I try to delete a specific amount of rows I get stuck.
Input:
sql = "SELECT COUNT(*) AS id FROM wifi_probe_requests";
...
sql = "DELETE FROM wifi_probe_requests LIMIT " + rowcount/2;
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.executeUpdate();
Output:
54943
[SQLITE_ERROR] SQL error or missing database (near "LIMIT": syntax error)
Not using a limit works fine and I can delete the entire db table but what I want is to delete half the db rows as seen by the rowcount/2 I made.
UPDATE:
So far I have solved the problem by finding the id which is located at the n-rows/2 and then getting the value of it (ex. 264352). Then using that number to indicate what id rows are going to be deleted (ex. id.value < 264352).
sql = "SELECT COUNT(*) AS id FROM wifi_probe_requests";
int rowcount = COUNT(*);
sql = "DELETE FROM wifi_probe_requests WHERE id < (SELECT id FROM wifi_probe_requests ORDER BY id ASC LIMIT "+ rowcount/2 + ",1)";
rowcount = 50000
Delete valueof.id < valueof.id.50000/2
So all values of id below the value of an id at position 25000 will be deleted.
You can't. Some databases don't allow LIMIT in UPDATE or DELETE queries.
It seems that with SQLite it's possible to work around that, by compiling your own version, but if you're not willing to do that, you need to rewrite your query in a different way. For example if you have an autoincrement id in the table, you can calculate the "middle" id and use WHERE id < [middle id] as an alternative to LIMIT.
As stated by #Kayaman this is not possible using SQLITE.
You can bypass this with a query such as;
DELETE FROM wifi_probe_requests WHERE id IN (SELECT id FROM wifi_probe_requests LIMIT 10)
One more thing; I don't think (rowcount/2) will work when you have an uneven amount of rows as it will not result in an integer. I think you will have to round it down/up.
How fancy do you want to make this? A simple solution would be something like:
SELECT COUNT(*) FROM mytable;
"SELECT id FROM mytable order by id LIMIT 1 OFFSET " + round(rowcount/2)
DELETE FROM mytable WHERE id < ?
If you go that route, you should be able to delete the first half of your rows by keyspace. If you just want just about half your rows deleted (and don't really care how many) you could probably find a way to use RANDOM() to do this. Probably like (WARNING TOTALLY UNTESTED):
DELETE FROM mytable WHERE random() < 0.5;

Use Value If Exists Else Use Default Value MySQL

Current Tools: Using Java to communicate with MySQL
I tried doing a search multiple times and ended up with this, but it didn't help me solve my problem. Google Search
I'm currently writing some query statements to try to save some information about my game objects to a database. I wanted to save the object's ID number if it wasn't 0, and to use the auto increment function otherwise if it was 0. For an example:
// (?,?) = (itemid, amount)
// itemid -> primary key and auto increment.
PreparedStatement ps = db.prepareStatement("INSERT INTO items (?,?)");
ps.setInt(1, item.id() == 0 ? >>>>DEFAULT<<<< : item.id());
ps.setInt(2, item.quantity());
The issue of course is that the way I'm doing isn't the correct way to tell MySQL to auto increment instead. Is there a way to do so? Also, the reason why I'm purposely inserting an ID in even though it's auto-increment is that I wrote a method previously that allowed me to save the original state of an item (thus preserving its stats). Upon loading this item, I want to be able to replace the current item and its stats with the newly loaded one.
Main Problem: Want to be able to insert a value if a condition is satisfied, otherwise use the auto-increment for primary key if possible. If there is something wrong with my approach, I'm open ears. Currently a beginner at databases!
EDIT:
As per MySQL suggestion, if you insert 0 into the id column, that column will automatically generate a sequence number.
Here: http://dev.mysql.com/doc/refman/5.7/en/example-auto-increment.html
Note that you should set the column (id) to AUTO-INCREMENT when the table is created. The auto increment will start at 1 so I you insert 0 the next max number will be inserted.
PreparedStatement ps = db.prepareStatement("INSERT INTO item(id, quantity) VALUES(?,?)");
ps.setInt(1, item.id());
ps.setInt(2, item.quantity());
Try it
PreparedStatement ps = db.prepareStatement("INSERT INTO items (?,?)");
ps.setInt(1, (item.id() == 0 ? 0 : item.id()));
ps.setInt(2, item.quantity());

java JDBC inserting many rows into tables

I have a csv file with 80 000 rows,
each rows have: cost;date (123.232;30/12/2008)
I have to insert all cost data into tables names as a date in parametr second for example:
123.232 cost will be row in a "30/12/2008" table
and i have so many rows like this..
Now my program looks like:
Now i have to declare SQL query in for loop because i need "date" parameter,
my question - how to draw a "pStatement = connection.prepareStatement("INSER...." line away from for loop ? ofcourse with getting "date" parameter
Why i need that?- because now addingBatch doesn't work and now add to database only last row.
If i will move pStatement.executeBatch() inside for loop- then that will not work like a batch addingbut like normally each adding.
I'm using batch adding because i need fast working my application.
All advice will be wanted
Database database = new Database();
Connection connection = database.GetConnection();
PreparedStatement pStatement = null;
for(int x=0; x<=allRowsInCSVFile.size()-1; x++){
Rows row = allRows.get(x);
pStatement = connection.prepareStatement("INSERT INTO \""+ row.getDate() +"\" (cost) VALUES (?);");
pStatement.setLong(1, row.getCost());
pStatement.addBatch();
}
pStatement.executeBatch();
connection.close();
I think you should split the allRowsInCSVFile to multiple lists each for one date then you can draw the prepared statement out of the loop (sort of). It will not be as you exactly want, but it will a batch for each date. I think that will be a compromise that you have to do.
not sure how good this is so ill post as community wiki
Object obj1 = new Object();
PreparedStatement pStatement =
connection.prepareStatement("insert into " + obj1.toString() );
while(true)
{
obj1.setSomeValue
}
You could use just jdbcTemplate.batchUpdate. See an example here: http://www.mkyong.com/spring/spring-jdbctemplate-batchupdate-example/
This allows you to use different sql but still execute in batch.
With preparedstatement you would have to group together all inserts with same date values and prepare different statements for each of those dates.

Java MySql preparedStatement

Hey I have problem with preparedStatement, I want to find min for few columns, I'm iterating over the names of columns and inserting them inside my preparedStatement like that
connection.prepareStatement("SELECT min( ? ) as min FROM test");
minStatement.setString(1, "some_column");
and when retrieving from ResultSet I'm getting the column name, in this case the result is "some_column" and should be 0. When using normal statement it does return right value.
I have no idea what I'm doing wrong.
Thanks for any help.
You cannot specify a column name in prepared statement like this, what you get is:
SELECT MIN('some_column') AS min FROM test
Instead of:
SELECT MIN(some_column) AS min FROM test
So, your query selects the minimal value 'some_column'... which is 'some_column'.
You could, instead, try that:
connection.prepareStatement("SELECT min(" + some_column + " ) as min FROM test");
But this may lead to injection attacks.

Prepared statement with wildcard not returning certain rows but query returns all rows?

I'm using JTDS as a driver to connect to SQL server.
Here's the query that's giving me problems:
SELECT EmpID,FirstName,LastName,CompanyName,DepartmentName,JobTitle,HireDate FROM Employees where UPPER(FirstName) LIKE 'KEVIN%'
It returns 2 rows on SQL Server. One that has 'KEVIN' in upper case and another that has 'Kevin' like so. I used the wildcard to make sure I get both results. In my EmployeeDAO class I'm using the following:
ps = con.prepareStatement("SELECT EmpID,FirstName,LastName,CompanyName,"
+ "DepartmentName,JobTitle,HireDate FROM Employees WHERE UPPER(FirstName) LIKE ?");
ps.setString(1, FirstName + "%");
rs = ps.executeQuery();
And then of course I put KEVIN on my main. It only returns ONE row, which is the 'Kevin' row.
How do I fix this so it returns all rows?
Your query looks fine (although I would uppercase the parameter value before setting it, to make it more robust). The problem is just in the way how you're collecting the rows from the ResultSet. Likely you're plain overriding the previous row with the next row so that you end up with only one row (the last one) in your collection.
Default collation of the SQL Server installation is SQL_Latin1_General_CP1_CI_AS and it is not case sensitive.
Change collation of the query:
SELECT Col1
FROM Table1
WHERE Col1 COLLATE Latin1_General_CS_AS LIKE 'KEVIN%'

Categories