Assign ID number automatically - java

strSQL = "INSERT INTO emp(NO, EMP_NAME, EMP_TEL)VALUES(088000, 'JIMMY', *****)";
stmt.executeUpdate(strSQL);
I have this statement to insert a new employee into the database.
What if I want the employee NO to be automatically generated by adding 1 to the previous employee NO? How can this be done in JSP?

While not JSP, a possible solution would be to create an auto generated incrementing column (known as an identity column) in the database. Importantly, this avoids the race condition that exists with a solution that retrieves the current maximum and increments it.
MySQL example:
create table emp (
emp_id integer not null auto_increment,
...
);
Apache Derby example:
create table emp (
emp_id integer not null generated always as identity,
...
);
MS SQL Server 2008 R2 example:
create table emp (
emp_id integer not null identity,
...
);
The INSERT statements do not include the emp_id column. See Statement.getGeneratedKeys() for obtaining generated id if required.

Depending of your DB... I give you a mysql example.
create table emp{
NO int unsigned auto_increment,
EMP_NAME varchar(30) not null,
...
}
insert into emp(EMP_NAME,...) values ("Jimmy", ...);
Now you can ask mysql the last inserted id with
LAST_INSERT_ID()

Yes of course, you can do this by setting "employee no" to be unique and A_I (auto_increament) in this column properties

Check database Schema where you are creating table emp with ID int NOT NULL AUTO_INCREMENT
Then update the schema strSQL = "INSERT INTO emp(EMP_NAME, EMP_TEL) VALUES('ABC_NAME', '321321')";
Though it is possible BUT we should not do any logical operation into JSP. Forward all input in Servlet and do there.

There are several way to do.
Some of databases like Oracle has features like sequence, which allows you to increment numbers sequently and operates as atomic.
Set the column (possibly primary key) to auto increment ( database option ), and do not specify that "NO" in your query. That way, the NO column you didn't add will be added by database automatically.
You can get max values from database table and add 1 for new NO, or you can save those latest value even in file, memcached, whatever you want. The problem of this #3 is, if you don't make program to be atomic between GET LATEST VALUE, ADD 1, CALL DATABASE INSERT QUERY, multiple query can have same NO to use. It's OK, however, if NO is primary key since only very first update/insert query will executed and others query will be failed due to primary key unique violation... but problematic in some cases.

You can use the AUTOINCREMENT option on the field NO on the database, or execute a query like SELECT MAX(NO) FROM emp
and get the max value

I think this will be going to solve your doubt in database and use this following query as:
CREATE TABLE:
CREATE TABLE `test` (
`id` INT(5) UNSIGNED NOT NULL AUTO_INCREMENT,
`emp_name` VARCHAR(50) NOT NULL,
`emp_tel` INT(5) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8
INSERT TABLE METHOD:1
INSERT INTO test
VALUES (0,jmail,1234567)OR(?,?,?);
INSERT TABLE METHOD:2
INSERT INTO test (id,emp_name,emp_tel)
VALUES (0,jmail,1234567);
If you had any doubt give me comment.
And if your using the sqlyog to use the shortcut.
if your wants this method like following as:
PreparedStatement ps = con.prepareStatement("INSERT INTO test(id,emp_name,emp_tel)
VALUES (0,jmail,1234567)");
ps.executeUpdate();
PreparedStatement ps = con.prepareStatement("INSERT INTO test(id,emp_name,emp_tel)
VALUES (?,?,?)");
ps.setString(1, id );
ps.setString(2, name);
ps.setString(3, tel);
ps.executeUpdate();

Related

JDBC. Replace in all rows value of the column

Java 11. PostgreSQL.
Having following table in db:
TABLE public.account (
id bigserial NOT NULL,
account_id varchar(100) NOT NULL,
display_name varchar(100) NOT NULL,
is_deleted bool NULL DEFAULT false,
);
There are about 1000 rows in this table. In the code I have a static method, which return random string - Helper.getRandomName()
How, using JDBC, in this table (public.account) for all rows replace "display_name" value with value of Helper.getRandomName()?
This is a SQL question. You need to run an update query:
UPDATE public.account set display_name = ?
And provide the new name as the parameter. The absence of a WHERE clause means that all rows will be affected.
If you want to do this for each row individually, then it's harder. You'll want to do a select statement to find all the IDs, and then you can prepare a batch of updates using JDBC, adding a where clause for each ID.
JDBC is just a thin Java wrapper around plain SQL execution.

How should my INSERT INTO statement for GENERATED BY DEFAULT AS IDENTITY be?

I'm trying to use GENERATED BY DEFAULT AS IDENTITY key for my record id's for my tables because a user needs to register themself and the user shouldn't be able to choose their own record id. So I decided to use GENERATED BY DEFAULT AS IDENTITY but I don't know how to write my INSERT statements.
This is my user table:
CREATE TABLE USER
(
ID_USER INT NOT NULL GENERATED BY DEFAULT AS IDENTITY,
USERNAME VARCHAR(20) UNIQUE NOT NULL,
FORENAME VARCHAR(20) NOT NULL,
SURNAME VARCHAR(20) NOT NULL,
PASSWORD VARCHAR(10) NOT NULL,
USER_TYPE INT NOT NULL,
PRIMARY KEY(ID_USER),
FOREIGN KEY (USER_TYPE) REFERENCES USER_TYPES(ID_TYPE)
);
and users will be allowed to register themselves.
This is what im using for my database
When a table has a column GENERATED BY DEFAULT AS IDENTITY it means that you can insert with a value in that column if you want to but you don't have to. So then in your insert, you could instead write
INSERT INTO ARTIST (ORIGIN,ARTIST_NAME) VALUES ('USA','Nirvana');
For reference: https://www.ibm.com/support/knowledgecenter/en/SSEPEK_11.0.0/apsg/src/tpc/db2z_identitycols.html
Edit after comment:
In the case where you need to retrieve the ID, #Mathias was correct that this is a duplicate question. A possible solution taken from this answer would be:
PreparedStatement result = cnx.prepareStatement(
"INSERT INTO ARTIST (ORIGIN,ARTIST_NAME) VALUES ('USA','Nirvana')",
RETURN_GENERATED_KEYS);
int updated = result.executeUpdate();
if (updated == 1) {
ResultSet generatedKeys = result.getGeneratedKeys();
if (generatedKeys.next()) {
int key = generatedKeys.getInt(1);
}
}
where key has the ID that you need for your next query.
The question is slightly different from the one already answered and needs a different answer.
The OP states: user shouldn't be able to choose their own record id. In that case the column definition should be ID_USER INT NOT NULL GENERATED ALWAYS AS IDENTITY to disallow any user-supplied value.
The table name shouldn't be USER as this is a reserved word. Try USERS instead.
The insert statement shouldn't insert into the ID_USER column. Similar to the example in the other answer, it should list the columns that are being inserted. An example below:
INSERT INTO USERS (USERNAME, FORENAME, SURNAME, PASSWORD, USER_TYPE)
VALUES ('JohnSmith','John', 'Smith', 'apasswrdx67', 3)
The OP wants to insert the generated value into another table using the GUI DatabaseManager. This is done by using the IDENTITY() function immediatly after inserting that row. For example,
INSERT INTO SOMETABLE (X, Y, Z) VALUES (IDENTITY(), 'some value', 'other value')

PostgreSQL unique string field

My database is PostgreSQL. The language is Java.
Table name is phrase with column name name.
At any time many users are inserting many rows to this table.
And we need to make sure that a certain field is unique.
And if such a field was found during loading, I want to return the row ID.
I could for example make a field the unique primary key, and when a row id inserted, catch the exception and look up the existing row.
But I think that is a bad idea.
I could just look for that row first and then insert.
But how can we avoid that the concurrent transactions get in each other's way?
And when downloading, is it better to do a batch download, and how do I do that in PostgreSQL? I do not even know.
You could create a UNIQUE constraint and INSERT ... ON CONFLICT:
CREATE TABLE mytable (
id integer PRIMARY KEY,
name text NOT NULL
CONSTRAINT name_unique UNIQUE
);
INSERT INTO mytable (id, name)
VALUES (1, 'me');
Now to run a batch INSERT that returns the id of each affecte row, run
INSERT INTO mytable (id, name)
VALUES (2, 'me'),
(3, 'new')
ON CONFLICT (name)
DO UPDATE SET name = EXCLUDED.name
RETURNING id;
The strange UPDATE that does not actually change the row is necessary if you want the id back.
Instead of catching the exception, you can use the INSERT ... ON CONFLICT DO NOTHING clause available in PostgreSQL. By checking the number of affected rows (returncode of PreparedStatement.executeUpdate), you can detect if there was a conflict.
E.g.
PreparedStatement pstmt = conn.prepareStatement("insert into x values (?,?) on conflict do nothing");
pstmt.setInt(1, myId);
pstmt.setInt(2, myValue);
int rc = pstmt.executeUpdate();
if (rc == 0) {
// fetch the existing row...
}

Java DB How to Insert Values for Foreign Keys into Table Column

I am using java DB database and NetBeans 8.0 for a desktop application
I am also using a PreparedStatement to query the database.
below is the code for creating the tables.
CREATE TABLE ALUMNUS (
ALUMNUA_ID INT NOT NULL PRIMARY KEY
GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
FIRST_NAME VARCHAR (45),
LAST_NAME VARCHAR (45),
OTHER_NAME VARCHAR (100)
);
CREATE TABLE DUES (
ID INT NOT NULL PRIMARY KEY
GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
PAYMENT_YEAR DATE,
AMOUNT DOUBLE,
ALUMNUS_ID INT
);
--FOREIGN KEY
ALTER TABLE APP.DUES
ADD FOREIGN KEY (ALUMNUS_ID) REFERENCES APP.ALUMNUS(ID);
Now I want to insert, delete and update the foreign key values in APP.DUES table. what is the best option; trigger , stored procedure or the preparedstatement?
An example will be good.
If you want to primarily insert into the DUES table, you would use a sub select in SQL. I havent tested it with Java DB, but it basically looks like:
INSERT INTO DUES(PAYMENT_YEAR, AMOUNT,ALUMNUS_ID)
VALUES(2014, 100.0,
(SELECT ALUMNUA_ID from ALUMNUS where ...));
You need to catch the "not found" error case and prepend a INSERT (and need to catch the duplicate case for that as well).
See also: Insert Data Into Tables Linked by Foreign Key

Java SQL simple update syntax issue

I have a table named books with bookID, bookName, count , orderCount
i'd like to write an sql query that will update all books.orderCount to books.orderCount+1.
How shall i do that using executeQuery("UPDATE books...."); ?
I'm having troubles with the syntax.
I've tried to search info on the net however most articles are about INSERT or DELETE commands and the only article that was related suggested to retrieve orderCount to Java, update it and then write it back to SQL. if possible i prefer to avoid it as it may cause serious problems (Locks on records are not needed for this task so i can not use them to avoid problems)
this should be pretty straight forward,
UPDATE books
SET orderCount = orderCount + 1
If it's about a primary key:
Also, you can AUTO INCREMENT.
CREATE TABLE Persons
(
P_Id int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
)
To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement:
ALTER TABLE Persons AUTO_INCREMENT=100
To insert a new record into the "Persons" table, we will not have to specify a value for the "P_Id" column (a unique value will be added automatically):
INSERT INTO Persons (FirstName,LastName)
VALUES ('Lars','Monsen')

Categories

Resources