I have made a table in oracle which uses auto incremented field thorough sequence.
Here is the sql:
CREATE TABLE Users(
user_ID INT NOT NULL,
user_name VARCHAR (20) NOT NULL,
user_password VARCHAR (20) NOT NULL,
user_role INT NOT NULL,
PRIMARY KEY (user_ID)
);
ALTER TABLE Users
ADD FOREIGN KEY (user_role) REFERENCES User_Roles (role_ID);
CREATE SEQUENCE seq_users
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10;
Now I need to insert the data into the table through a java program, is there any way, I don't have to use the query like this:
Insert into User_Roles values (seq_user_roles.nextval,'system admin');
User Role Table:
CREATE TABLE User_Roles(
role_ID INT NOT NULL,
role_name VARCHAR (20) NOT NULL,
PRIMARY KEY (role_ID)
);
CREATE SEQUENCE seq_user_roles
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10;
I want to insert the data from a java program and can't specify that name of the sequence.
Crete below trigger after sequence creation. So it will populate date into your column. And no need to mention role_id column in you insert statement script.
CREATE OR REPLACE TRIGGER TRG_User_Roles_BRI
BEFORE INSERT
ON User_Roles
REFERENCING NEW AS NEW OLD AS OLD
FOR EACH ROW
BEGIN
:NEW.role_ID := seq_user_roles.NEXTVAL;
END;
Related
I was trying to create a new object and this error appeared:
java.sql.sqlexception failed to read auto-increment value from storage engine
So I went to the phpMyAdmin to create the object there and the same showed up:
MySQL said: Documentation
1467 - Failed to read auto-increment value from storage engine
then I clicked on edit, and it was there:
INSERT INTO `reservation`.`room` (`idroom`, `number`, `floor`, `description`, `characteristics`, `cost`, `status`, `type`) VALUES (NULL, '114', '3', 'ss', 'ss', '550.00', 'Available', 'ss')
(idroom is supposed to be auto-incremented.)
I already read other posts where they say I have to put this:
ALTER TABLE `table_name` AUTO_INCREMENT = 1
but I have no idea where to put that. Is there a better solution?
Your INSERT statement is wrong. Since idroom is AUTO_INCREMENT; you must not include it in the column list on your insert command. Your insert statement should look like below. Notice that I have removed idroom column from insert column list and not passing NULL as well in value list.
INSERT INTO `reservation`.`room` (`number`, `floor`, `description`,
`characteristics`, `cost`, `status`, `type`)
VALUES ('114', '3', 'ss', 'ss', '550.00', 'Available', 'ss')
I also struggled with this problem and searched, and didn't find anything. Then the following worked for me; I guess it might work for your problem. Thx.
1st:
-delete (before backup)->all data from your database.
-try to run your Java program again, or any program you want.
If it fails then go to 2nd.
2nd:
- backup all data from your table
- delete table completely
- create table again; example shown below:
CREATE TABLE `users` (
`id` int(6) NOT NULL,
`f_name` varchar(30) NOT NULL,
`l_name` varchar(30) NOT NULL,
`address` varchar(50) DEFAULT NULL,
`phone_num` varchar(12) DEFAULT NULL,
`email` varchar(30) DEFAULT NULL
);
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
AUTO_INCREMENT for table `users`
ALTER TABLE `users`
MODIFY `id` int(6) NOT NULL AUTO_INCREMENT;
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
I have 2 tables Customers & Accounts in my Oracle Database. I have sequence numbers for generating surrogate key values for both tables.
CREATE SEQUENCE customers_seq NOCACHE;
CREATE SEQUENCE accounts_seq NOCACHE;
CREATE TABLE customers
(
customer_surrogate_id NUMBER(10),
customer_id VARCHAR2(8) UNIQUE NOT NULL,
customer_password VARCHAR2(20),
customer_name VARCHAR2(20),
customer_pan VARCHAR2(10) UNIQUE,
customer_email_id VARCHAR2(20) UNIQUE,
CONSTRAINT customer_pk
PRIMARY KEY (customer_surrogate_id)
);
CREATE TABLE accounts
(
accounts_surrogate_id NUMBER(10),
account_id VARCHAR2(10) UNIQUE NOT NULL,
customer_surrogate_id NUMBER(10),
account_type VARCHAR2(10),
account_currency VARCHAR2(20),
account_balance NUMBER(20, 2),
CONSTRAINT accounts_pk
PRIMARY KEY (accounts_surrogate_id),
CONSTRAINT accounts_fk
FOREIGN KEY (customer_surrogate_id)
REFERENCES customers(customer_surrogate_id)
);
I know how to use sequence_name.NEXTVAL & sequence_name.CURRVAL in insert statements to perform the reference
The problem is with using NEXTVAL & CURRVAL is that it assumes that inserts to both tables occur sequentially like
insert into Customers(// use NEXTVAL here)
insert into Accounts(// use CURRVAL here to reference the above row in Customers)
But in my java application, the multiple inserts for the Customers table can occur before even one insert occurs in Accounts table. CURRVAL will return the value of the last inserted row of the Customers table.
When inserting a row into Accounts table, I can get customers_id values in my application. Should the customer_id be used to query the Customers table to get the customer_surrogate_id as shown below?
insert into Customers(// use NEXTVAL here)
...
insert into Accounts(// use the customer_id to query and find customer_surrogate_id)
Is there better way to reference the Customers table in this situation?
Edit: I am using JDBC to access the database.
Simply select the value, and store it in a variable:
long customer1Id = selectNextValueFromSequence("customers_seq");
long customer2Id = selectNextValueFromSequence("customers_seq");
insertCustomerWithId(customer1Id);
insertCustomerWithId(customer2Id);
insertAccountWithCustomerId(customer1Id);
insertAccountWithCustomerId(customer2Id);
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();
I've two tables that has defined as below; From user table, hospitalId and poliklinikId both references table relhospol, and if any row is deleted from relhospol, (if any user is related with it), I want to set the hospitalId and poliklinikId null, DDL says that. When i delete a row from SQLite Manager it nulls the User's hospitalId and PoliklinikId, However when i try to remove a row from application level (Java), it only removes from relhospol, it does not set null (hospitalId, PoliklinikId) What is the missing point ?
JDBC Driver: SQLite-jdbc-3.7.2
CREATE TABLE [USER] (
[ID] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
[GROUPID] INTEGER CONSTRAINT [FK_USER_GID] REFERENCES [GROUP]([ID]) ON DELETE SET NULL ON UPDATE CASCADE,
[HOSPITALID] INTEGER,
[POLIKLINIKID] INTEGER,
[NAME] VARCHAR(50) NOT NULL,
[LOGINID] VARCHAR(15) NOT NULL,
[EMAIL] VARCHAR(50) NOT NULL,
[PASSWORD] VARCHAR(32) NOT NULL,
CONSTRAINT [FK_USER_RELHOSPOL] FOREIGN KEY([HOSPITALID], [POLIKLINIKID]) REFERENCES [RELHOSPOL]([HOSPITALID], [POLIKLINIKID]) ON DELETE SET NULL ON UPDATE CASCADE);
CREATE UNIQUE INDEX [AS] ON [USER] ([LOGINID]);
CREATE UNIQUE INDEX [AS1] ON [USER] ([EMAIL]));
CREATE TABLE [RELHOSPOL] (
[HOSPITALID] INTEGER CONSTRAINT [FK_RELHOSPOL_HOS] REFERENCES [HOSPITAL]([ID]) ON DELETE SET NULL ON UPDATE CASCADE,
[POLIKLINIKID] INTEGER CONSTRAINT [FK_RELHOSPOL_POL] REFERENCES [POLIKLINIK]([ID]) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT [sqlite_autoindex_RELHOSPOL_1] PRIMARY KEY ([HOSPITALID], [POLIKLINIKID]));
You can't set NULL a primary key:
CREATE TABLE [RELHOSPOL] (
[HOSPITALID] INTEGER CONSTRAINT [FK_RELHOSPOL_HOS] REFERENCES [HOSPITAL]([ID]) ON DELETE SET NULL ON UPDATE CASCADE,
[POLIKLINIKID] INTEGER CONSTRAINT [FK_RELHOSPOL_POL] REFERENCES [POLIKLINIK]([ID]) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT [sqlite_autoindex_RELHOSPOL_1] PRIMARY KEY ([HOSPITALID], [POLIKLINIKID]));
You are trying to remove a row from which table? Can you post the DELETE SQL?
Ok I've changed the RELHOSPOL's definition as below; When i delete row from RELHOSPOL from the SQL Manager with executing a DELETE command, it nulls the necessary rows at the USER table. Whenever I delete a row from application with the method written below, it only deletes row from RELHOSPOL, and does not SET NULL the necessary rows at USER table
CREATE TABLE [RELHOSPOL] (
[ID] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
[HOSPITALID] INTEGER,
[POLIKLINIKID] INTEGER);
CREATE UNIQUE INDEX [UNIQUE_RELHOSPOL] ON [RELHOSPOL] ([HOSPITALID], [POLIKLINIKID]);
Delete Method is :
public void deletePoliklinikFromHospital(int hospitalId, int poliklinikId) throws SQLException{
String query = "DELETE FROM [RELHOSPOL] WHERE (HOSPITALID = ? AND POLIKLINIKID = ?)";
try {
PreparedStatement statement = db.prepareStatement(query);
statement.setInt(1, hospitalId);
statement.setInt(2, poliklinikId);
statement.executeUpdate();
} catch (SQLException e) {
throw new SQLException(e.getMessage());
}
}
It is just a guess, but maybe you are not aware, that you have to enable foreign key support with PRAGMA foreign_keys = ON; everytime you connect to the database? If this is not done, your statements will be parsed, but not enforced. This could explain, why it is working from SQLite Manager.
One should also be aware, that old versions of Sqlite (<3.6.19) will tolerate the syntax but too will not enforce anything.
As sidenote:
As #Neuquino writes the ON DELETE SET NULL statements for table RELHOSPOL don't seem to make sense.