get the next id - mysql

My question is how to get the next id using NHibernate in a mysql db for an auto-increment ID column ?
Thanks,

Based on the further description you give (as an answer?) below it seems to me that you are indeed looking for the NHibernate feature to automatically read back IDs generated by the database: identity
This will tell NHibernate the ID's value is determined by the database upon insert, it will not send a value as part of its INSERT statement and it will read back the value of the ID column after it has performed the insert. But you do have to tell the database (in the table definition) that it should auto-generate a value for the ID column for each record inserted...

You're going to create a race condition if you do this. To answer your question, I don't think there is a specific way for Hibernate to give you this information since no application can give you this information. By getting the "next id", by the time it returns that data to you, it might be invalid already. The easiest way I can think of is to get the last_insert_id() and add +1 to it.
Why don't you post more information about you're trying to accomplish and we can find a better solution for you?

Provided that you are the only writer to your database then you could get your application to maintain the sequence number for you and allocate the next number yourself.
If you want to do this then you'll want to ensure that your application counter is thread safe.
You'll also want a way to get the last written sequence number when restarting you application.

Related

How to handle user status in MySQL using sequelize

I have user's who's status could be active,pending,rejected,de-active,so what is appropriate way to handle status.
I have two scenarios in my mind
1. i can handle it by isPending,isRejected,isActive ,isDe-active flags
2. i can use status flag and can pass 0,1,2,3 corresponding
so my question is what is best way to handle status in MySql, is there any other scenarios
if you know anyone who can help pleas tag them
I believe using a status integer would be a better idea for the following reasons:
Your users can only have one active status at a time, so having only one column enforces that constraint.
In the case where you would like to add another status (for example, expired, if you want to create temporary users), multiple flags would require you to change your schema, as the single column solution would just require you to change your code.
Checking the user status with the first solution requires you to check all these booleans.
Changing the user status with the first solution requires you to update multiple columns as the other solution requires only one column to be updated.

best way to get the last inserted record in sql server

Hi all I having a Identity column and a Computed primary key column in my table I need to get the last inserted record immediately after inserting the record in to database, So I have written the following queries can some one tell which is the best one to choose
SELECT
t.[StudentID]
FROM
[tbl_Student] t
WHERE
t.ID = IDENT_CURRENT('tbl_Student')
The other is using MAX as follows
Select
MAX(StudentID)
from tbl_Student
From the above two queries which is the best one to choose.
MAX and IDENT_CURRENT, according to technet, would behave much the same and both would be equally unreliable.
"IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope. For more information, see IDENT_CURRENT (Transact-SQL)."
Basically, to return the last insert within the current scope, regardless of any potential triggers or inserts / deletes from other sessions, you should use SCOPE_IDENTITY. Of course, that's assuming you're running the query in the same scope as the actual insert in the first place. :)
If you are, you also have the alternative of simply using OUTPUT clause to get the inserted ID values into a table variable / temporary table, and select from there.
The original answer, where my assumptions about IDENT_CURRENTwhere wrong.
Use the first one. IDENT_CURRENT should give you the last item for the current connection. If someone else would insert another student concurrently IDENT_CURRENT will give you the correct value for both clients, while MAX might give you a wrong value.
EDIT:
As it was mentioned in the other answer IDENT_CURRENTand MAXare equally unreliable in case of concurrent usage. I would still go for IDENT_CURRENT but if you want to get the last identity used by the current scope or session you can use the functions ##IDENTITY and SCOPE_IDENTITY. This technet article explains the detailed differences between IDENT_CURRENT, ##IDENTITY and SCOPE_IDENTITY.

Increment a value in mysql table column dynamically

I have a mysql table column (runs) which holds an integer, I want to increment it by another dynamic value (1,2,3,4,5) using an update query on click of a button. How should I do that?
(Without retrieving the original value from that table column, is there any direct way to increment the value, not like AUTO_INCREMENT since it does it using a static value)
I've checked the documentation on MySql here and it seems you can do it with an update query like this:
UPDATE t1 SET col1 = col1 + 1;
where you can change 1 to any numeric value as long as col1 is also numeric.
MySql will get the initial value of col1 and add your number to it.
Even if MySql can do this, I'm guessing this also has an impact on speed, it might be faster then 2 queries, but probably needs testing to determin the differences.
When confronted with software speeds issues saving a select query for only one value it's not the key modification that you can do to optimize your app. As Digvijay Yadav suggested, you should also check other solutions, and other optimizations on to make your app faster.
another example on that page that also shows that what your are trying to do can work is :
UPDATE t SET id = id + 1 ORDER BY id DESC;
please try it and let me know if it doesn't work.
If DB interaction is the main problem then in this case I would suggest not to read/write to DB on every user click. Instead you should retrieve the value once and store them in a DS (may be an array or list). On every click you perform operations on this list and after sometime you update the DB with updated values.
Also, if you are creating and destroying the DB connections on every read/write operation then I would not suggest that. A better solution IMO is to create a DB connection when your webapp starts up and store the connection object in the ServletContext as an attribute as you are using servlets and JSPs.
Further if your web app is too big and has thousand of users then there are several caching techniques for improving the performance of DB.

Perl MySQL - How do I skip updating or inserting a row if a particular field matches?

I am pretty new to this so sorry for my lack of knowledge.
I set up a few tables which I have successfully written to and and accessed via a Perl script using CGI and DBI modules thanks to advice here.
This is a member list for a local band newsletter. Yeah I know, tons of apps out there but, I desire to learn this.
1- I wanted to avoid updating or inserting a row if an piece of my input matches column data in one particular column/field.
When creating the table, in phpmyadmin, I clicked the "U" (unique) on that columns name in structure view.
That seemed to work and no dupes are inserted but, I desire a hard coded Perl solution so, I understand the mechanics of this.
I read up on "insert ignore" / "update ignore" and searched all over but, everything I found seems to not just skip a dupe.
The column is not a key or autoinc just a plain old field with an email address. (mistake?)
2- When I write to the database, I want to do NOTHING if the incoming email address matches one in that field.
I desire the fastest method so I can loop through their existing lists export data, (they cannot figure out the software) with no racing / locking issues or whatever conditions in which I am in obvious ignorance.
Since I am creating this from scratch, 1 and 2 may be in fact partially moot. If so, what would be the best approach?
I would still like an auto increment ID so, I can access via the ID number or loop through with some kind of count++ foreach.
My stone knife approach may be laughable to the gurus here but, I need to start somewhere.
Thanks in advance for your assistance.
With the email address column declared UNIQUE, INSERT IGNORE is exactly what you want for insertion. Sounds like you already know how to do the right thing!
(You could perform the "don't insert if it already exists" functionality in perl, but it's difficult to get right, because you have to wrap the test and update in a transaction. One of the big advantages of a relational database is that it will perform constraint checks like this for you, ensuring data integrity even if your application is buggy.)
For updating, I'm not sure what an "update ignore" would look like. What is in the WHERE clause that is limiting your UPDATE to only affect the 1 desired row? Perhaps that auto_increment primary key you mentioned? If you are wanting to write, for example,
UPDATE members SET firstname='Sue' WHERE member_id = 5;
then I think this "update ignore" functionality you want might just be something like
UPDATE members SET firstname='Sue' WHERE member_id = 5
AND email != 'sue#example.com';
which is an odd thing to do, but that's my best guess for what you might mean :)
Just do the insert, if data would make the unique column not be unique you'll get an SQL error, you should be able to trap this and do whatever is appropriate (e.g. ignore it, log it, alert user ...)

How to mark posts as edited?

I would like to have questions marked as "Edited", but I dont know what the best way to do this would be.
Users post a question, people answer/comment on the question, and if necessary the user edits/updates the question (just like SO). I would like to note that the user edited the question, but I'm not sure of the best way to do this.
I was going to add a last_edited column in the table (because thats all thats really important to me), but I'm not sure if I should just split the edit times (and whatever else) into another table and record everytime the question gets edited.
EDIT: UIf I were to use a timestamp, what time would be used? Is there any way to insert a unix timestmap on update?
This depends on whether anyone (users or admins) ever cares about history of edits.
If they do, definitely split into another table
If all what you want is a mark Edited or not, you can just add a Timestamp column in the same table, populated to NULL by default, then populated by last update timestamp.
On the page if its populated then display its value, otherwise don't display the Edited icon/symbol.
If you only care about when the most recent update occurred, add a timestamp column in the same table.
If you'd like to keep track of every edit that's occurred, create a separate table that contains question_id and the timestamp.
Depending on how you're processing your date/time data, you can either store the unix time stamp (fieldname = unix_timestamp(now())), or as a regular mysql datetime field (fieldname=now()).
If you're going to do data sorting/filtering based on dates/times in mysql, then use the native datetime type so you can take direct advantage of all of mysql's date&time processing functions. If you're going to do most of the processing in your application, a unix timestamp tends to be more portable than a formatted date/time string.
As for the table structure, the simplest way to track edits is a pair of fields (lastedited, and lasteditor). If you want to keep a full list of editors and times, then you'll need a seperate table. If you're keeping track of the changes, then the versioning/trakcing information can go into the same table.