Use Value If Exists Else Use Default Value MySQL - java

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());

Related

JDBC: Generating the value of primary key for prepared statements [duplicate]

This question already has answers here:
Is there a way to retrieve the autoincrement ID from a prepared statement
(5 answers)
Illegal operation on empty result set [duplicate]
(2 answers)
Closed 7 years ago.
Suppose I want to add a new row to my table via JDBC. In my table, I have an auto incrementing primary key field (so I can update the table later), and another regular field.
userid BIGINT AUTO_INCREMENT PRIMARY KEY,
username TEXT,
Now, I am creating the new statement and executing it using prepared statements, like so:
//dummy execute to get the generated keys
stmt.execute("SELECT * FROM user;", Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stmt.getGeneratedKeys();
int id=1;
//this is never executed, the resultset is always empty...
if(rs.next())
{
System.out.println("not empty");
id = rs.getInt(1);
}
System.out.println(id); //therefore, id is always 1
//prepare a statement to execute in SQL
stmt=con.prepareStatement("INSERT INTO user VALUES (?,?);", Statement.RETURN_GENERATED_KEYS);
//fill in the ?'s with their respective values
((PreparedStatement) stmt).setString(1, String.valueOf(id));
((PreparedStatement) stmt).setString(2, user);
//execute statement
((PreparedStatement) stmt).executeUpdate();
As you see, I want the value of the generated key so that I can use a prepared statement to update all the columns in the newly generated row (otherwise I get a No value specified for parameter 1 error).
But when I do the above code, I get an
Duplicate entry '1' for key 'PRIMARY'
This seems to me that the resultset is always empty. So I am not accessing the value correctly. Why is this so, and how can I fix this so that I can use my same structure of prepared statements to execute these queries?
You can call getGeneratedKeys only after you have executed you statement, not before. See https://docs.oracle.com/javase/8/docs/api/java/sql/Statement.html#getGeneratedKeys--
Simply preparing the statement does not generate the new key. Just drop the id column from your insert and insert only user.
1.Since your id is Auto Increment Column you should pass the value for that filed for first time (try to do it through MYSQL server directly.
2.Don't try to perform operations on empty result set.
3.In your case id always will be 1 since if statement doesn't execute.
Thank you.

Mysql Duplicate entry 'xxxxxxxx' for key(unique) 'xxxxxxxxxx'

I have a problem of updating a row. I have a column called serialNum with varchar(50) not null unique default null
When I get the response data from the partner company, i will update the row according to the unique serial_num (our company's serial num).
Sometimes update failed because of :
Duplicate entry 'xxxxxxxx' for key 'serialNum'
But the value to update is not exists when i search the whole table. It happens sometimes, not always, like about 10 times out of 300.
Why does this happen and how can I solve it?
below is the query i use to update:
String updateQuery = "update phone set serialNum=?, Order_state=?, Balance=? where Serial_num=" + resultSet.get("jno_cli");
PreparedStatement presta = con.prepareStatement(updateQuery);
presta.setString(1, resultSet.get("oid_goodsorder"));
presta.setString(2, "order success");
presta.setFloat(3, Float.valueOf(resultSet.get("leftmoney")));
presta.executeUpdate();
I think the reason is in resultSet.get("oid_goodsorder") where did you get this result? is 'oid_goodsorder' is unique? Did you always updates whole table?
If oid_goodsorder is unique, it is possible to have duplicates in serialNum, because you don't use bulk update, instead you update every record separately, therefore it is possible:
Before:
serialNum=11,22,33,44
oid_goodsorder=44,11,22,33
It tries to update first serialNum to 44, but 44 is exists!
But if you finish all update serialNum will be unique...
If you wants to get error rows you could disable set serialNum is not unique and check table for duplicating serialNum
If you don't have duplicating values try to use bulk update
Java - how to batch database inserts and updates

How to get the serial id just after inserting a row? [duplicate]

This question already has answers here:
How to get a value from the last inserted row? [duplicate]
(14 answers)
Closed 9 years ago.
I have a table with row 'id' (a primary key) default set to serial in PostgreSQL. I insert into this row by calling
session.getCurrentSession().createSQLQuery("some insert query")
without adding any value into id as it is default set to serial.
How can I retrieve the `id' of just inserted row?
JDBC statements can return the generated keys. For instance, if the table has a single column id of type serial (probably PK) that is not mentioned in the insert SQL below, the generated value for this column can be obtained as:
PreparedStatement s = connection.createStatement
("INSERT INTO my_table (c,d) VALUES (1,2)",
Statement.RETURN_GENERATED_KEYS);
s.executeUpdate();
ResultSet keys = s.getGeneratedKeys();
int id = keys.getInt(1);
This is faster than sending the second query to obtain the sequence value or max column value later. Also depending on circumstances these two other solutions may not be not be thread safe.
Since it is serial you can use select max(id) from tableName
Using max(id) is a very bad idea. It will not give you the correct result
in case of multiple concurrent transactions. The only correct way is to use
curval() or the returning clause.
In posgresql: There is already a stackoverflow-question exists BTW.
`INSERT INTO tableName(id, name) VALUES(DEFAULT, 'bob') RETURNING id;`
(also)
Get a specific sequence:
SELECT currval('name_of_your_sequence');
Get the last value from the last sequence used:
SELECT lastval();
Manual: http://www.postgresql.org/docs/current/static/functions-sequence.html
For PHP-mysql users:
From php.net clickhere
<?php
$link = mysqli_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysqli::$connect_error() );
}
mysqli::select_db('mydb');
mysqli::query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysqli::$insert_id());
?>
But you need to connect for every query.
use SELECT CURRVAL(); . Typically used in conjunction with pg_get_serial_sequence
postgreSQL function for last inserted ID

How to get numbers of affected rows in sqlite

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?

setXXX methods of PreparedStatement not working

I got something like this.
PreparedStatement statement = manager.getConnection().prepareStatement("delete from student_marks where reg_number = ? and semester = ?");
statement.setInt(1,1);
statement.setString(2,"S1");
System.out.println(statement.executeUpdate());
But the executeUpdate is returning 0 when I do this. If I directly replace the '?' with the values, then executeUpdate is woriking properly. In my case, it returned 4 meaning that 4 rows were deleted. I am not able to understand where the problem lies.
It depends on your column type... If column type for reg_number is number(any numeric data type), then only you must set it integer, else otherwise you must set it using string.
PreparedStatement statement = manager.getConnection().prepareStatement("delete from student_marks where reg_number = ? and semester = ?");
statement.setString(1,"1");
statement.setString(2,"S1");
System.out.println(statement.executeUpdate());
As jlordo pointed out, Did you reinsert the records before deleting it next time?

Categories