Using Auto Increment with MySQL and need to retrieve that number - java

I have a database in which I need some IDs to be autoincremented, but I also need that ID that gets auto incremented to be the Foreign Key for another table. Is there a way to recover that number within the same transaction to insert values into the second table?
As in:
1) Create a user
2) Retrieve the ID number generated by the auto increment ( for example: AI:5 )
3) Insert values into a table called Doctor, that needs that number retrieved by that user, all within same transaction...
I know that JSP has some function to recover that ID generated but not sure about MySQL.
Another thing is, I can't just send a query to recover the last generated ID because for example if 10 accounts got created at the same time I might not get the supposed number.

For a pure MySQL solution:
SELECT LAST_INSERT_ID();
For a Java way:
ResultSet rs = stmt.getGeneratedKeys();

Related

Mysql and JDBC returned stale data

We are facing a strange issue with mysql data. We have a seqgenerator table which holds the current seq of the id. Every time an order is placed my application queries the seqgenerator table and updates one number and saves it back in the seqgenerator.
The query we are using to fetch is "select order_id from order_seq where appid = ? for update"
Query to update "update order_seq set order_id = ? where appid = ?"
This was working fine until last week, last week the select query returned id which was already used one day back and the id got reset and started incrementing from there due to which we have overridden 1 days orders.
Your design is just very bad.
First of all, Id should always be unique, this would have prevented your data from being overwritten.
Also SQL has an Auto-Increment field, so you don't have to update your ID by one each time
Auto-increment allows a unique number to be generated automatically
when a new record is inserted into a table.
Often this is the primary key field that we would like to be created
automatically every time a new record is inserted
Source:
https://www.w3schools.com/sql/sql_autoincrement.asp

H2 database auto-incremented id's have random values after first entry

I created database table with query:
"CREATE TABLE downloads(id BIGINT PRIMARY KEY AUTO_INCREMENT,...
When i insert anything into table first time ID thats generated for entry is 1
Second time its 100% of the time random value 1,33,65,97,129,161,193,225,226,227 etc
Is there a way to set my database to auto increment normally? 1 ,2 ,3 ,4 etc, To me the ID number doesnt matter bud i have to be able to predict next ID that will be present for an entry beforehand.If there is a way to predict or get id thats gonna be generated for my entry i might as well use that,IF IT DOESNT CREATE ANY GREAT OVERHEAD.
So my quesiton is why im gettin random values for id?
Is there a way to set autoincrement to ordinary +1?
Can i get id value before its generated if there is no way to set autoincrement to +1 style?
Only option that i use for my connection is ;DATABASE_TO_UPPER=false
Query to insert data
getConnection().prepareStatement("INSERT INTO downloads(state,name,size,source,added,completedOn,downloadDir) VALUES(?,?,?,?,?,?,?)",Statement.RETURN_GENERATED_KEYS);
EDIT:After creating new database, numbers are exactly the same every time so these values aint random.First 3 values i entered had id's 1,33,65
Found out that problem was in PRIMARY KEY part of the query...
After removing it from there and making yet another db, everything is working now.

Capture values from JDBC requests and use for next query

I'm trying to use Jmeter with about 10 queries per thread. All I want each thread to do is Insert into a player table using mysql auto increment. Then I want to use mysql
SELECT last_insert_id();
to grab the auto inc value and use it for the next query which is inserted into a player_game table.
How do I store the value returned and how do I call it in the next query?
I tried to save it in the variable name but can't seem to get it to insert correctly on the next query.
I then tried to call it using both ${player1id} and player1id but couldn't get it to work.
Is there a better way to go about this?
Or how can I store that value for the next JDBC request?
Both the queries
Insert into player...
Insert into player_game...
have auto increment on player_id and player_game_id
I then need to insert into a third table player_game_round and I need to insert the values from both player_id and player_game_id as such:
INSERT INTO player_game_round (round, player_score, player_id, player_game_id)....
You can directly do
INSERT into player_game(player_id, game_id) values(last_insert_id(), 1);

Locking Tables with postgres in JDBC

Just a quick question about locking tables in a postgres database using JDBC. I have a table for which I want to add a new record to, however, To do this for the primary key, I use an increasing integer value.
I want to be able to retrieve the max value of this column in Java and store it as a variable to be used as a new primary key when adding a new row.
This gives me a small problem, as this is going to be modelled as a multi-user system, what happens when 2 locations request the same max value? This will of course create a problem when trying to add the same primary key.
I realise that I should be using an EXCLUSIVE lock on the table to prevent reading or writing while getting the key and adding a new row. However, I can't seem to find any way to deal with table locking in JDBC, just standard transactions.
psuedo code as such:
primaryKey = "SELECT MAX(id) FROM table1;";
primary key++;
//id retrieved again from 2nd source
"INSERT INTO table1 (primaryKey, value 1, value 2);"
You're absolutely right, if two locations request at around the same time, you'll run into a race condition.
The way to handle this is to create a sequence in postgres and select the nextval as the primary key.
I don't know exactly what direction you're heading and how your handle your data, but you could also set the column as a serial and not even include the column in your insert query. The column will automatically auto increment.

Get a unique max id for each instance using mysql

I am using a field with a prefix + auto increment id. For each instance i am taking the max+1 of ID and adding that to prefix. Can anyone suggest me a way to get this as unique please?
You can try this:
Insert into table1 (id, user_id)
SELECT MAX(id)+1, CONCAT('a',CAST(MAX(id)+1 AS char))
FROM table1;
See this SQLFiddle
The problem with using max(id)+1 is that there may be multiple threads making the same call, and so the result would not be unique. There are several ways to solve this problem. The first is to use a sequence, where the database server will increment the number every time a new id is requested. You can use a table, with a number in it, but you have to lock the table when you update the number. Or you can allow the database to create the key for you when the table is inserted and retrieve the key after the insert. All are valid.
I prefer to use Hibernate and make it determine how to implement the ID for the database I am currently using.

Categories