i am trying to set my ID to auto_increment, but it is not doing it. i saved 2 more data into db, all are still getting 0 id. as a result i am not able to set ID as primary key.
how is it possible? can i set the field to auto_increment with JPA annotation or so?
i even tried this command which is the first attempt:
alter table user alter column id int not null auto_increment;
no affect.
can someone help me please
thanks in advance!
If you just want to set ID as a primary key which is auto generated,then sql uniqueidentifier for it.
CREATE TABLE userTable(userId uniqueidentifier primary key, userName nvarchar(50))
--create a table having userId as a primary key
INSERT INTO userTable(userId, userName ) VALUES (NEWID(), 'mohit');
INSERT INTO userTable(userId, userName ) VALUES (NEWID(), 'doniyor');
SELECT * FROM userTable
Result will be:
userId userName
{E8E0A79D-436F-49CB-BCEC-EC9E5D69F1BB} mohit
{21081DFA-7DBB-46AF-A160-550631160C25} doniyor
Related
I'm trying to implement a users authentication table. I'm on user registration and my console prints out:
org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Unique index or primary key violation: "PUBLIC.USERS_USERNAME_UINDEX ON PUBLIC.USERS(USERNAME) VALUES 1"; SQL statement:
INSERT INTO USERS(FIRST_NAME,LAST_NAME,USERNAME,PASSWORD) VALUES(?,?,?,?) [23505-200]
I don't really understand why. My table's SQL script is as follows:
-- auto-generated definition
create table USERS
(
USER_ID INT auto_increment,
USERNAME VARCHAR2,
FIRST_NAME VARCHAR2,
LAST_NAME VARCHAR2,
PASSWORD VARCHAR2,
constraint USERS_PK
primary key (USER_ID)
);
create unique index USERS_USERNAME_UINDEX
on USERS (USERNAME);
create unique index USERS_USER_ID_UINDEX
on USERS (USER_ID);
I want username to be unique for each entry so I set that field as unique. This is how I populate it:
Connection connection = new InitialiseDatabase().getConnection();
String sql = "INSERT INTO USERS(FIRST_NAME,LAST_NAME,USERNAME,PASSWORD) VALUES(?,?,?,?)";
PreparedStatement myStatement = connection.prepareStatement(sql);
myStatement.setString(1, txtFirstName.getText().trim());
myStatement.setString(2, txtLastName.getText().trim());
myStatement.setString(3, txtUsername.getText().trim());
String hashed = BCrypt.hashpw(txtPassword.getText(), BCrypt.gensalt());
myStatement.setString(4, hashed);
myStatement.executeUpdate();
How can I get around this?
My table is being populated with the data though. So I don't understand what exactly is wrong. Any help would be appreciated.
A UNIQUE index makes sure that two rows cannot have same value for the unique indexed column.
https://www.oracletutorial.com/oracle-index/oracle-unique-index/
Unique index or primary key violation: "PUBLIC.USERS_USERNAME_UINDEX ON PUBLIC.USERS(USERNAME)
is pretty much talking. You're probably inserting a new row with a same value of username already inserted previously.
My table is being populated with the data though
Make sure your DB does not already have same value you're trying to insert.
I have a pre-existing table, containing 'fname', 'lname', 'email', 'password' and 'ip'. But now I want an auto-increment column. However, when I enter:
ALTER TABLE users
ADD id int NOT NULL AUTO_INCREMENT
I get the following:
#1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key
Any advice?:)
Try this
ALTER TABLE `users` ADD `id` INT NOT NULL AUTO_INCREMENT;
for an existing primary key
If you don't care whether the auto-id is used as PRIMARY KEY, you can just do
ALTER TABLE `myTable` ADD COLUMN `id` INT AUTO_INCREMENT UNIQUE FIRST;
I just did this and it worked a treat.
If you want to add AUTO_INCREMENT in an existing table, need to run following SQL command:
ALTER TABLE users ADD id int NOT NULL AUTO_INCREMENT primary key
First you have to remove the primary key of the table
ALTER TABLE nametable DROP PRIMARY KEY
and now yo can add the autoincrement ...
ALTER TABLE nametable ADD id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
Well, you must first drop the auto_increment and primary key you have and then add yours, as follows:
-- drop auto_increment capability
alter table `users` modify column id INT NOT NULL;
-- in one line, drop primary key and rebuild one
alter table `users` drop primary key, add primary key(id);
-- re add the auto_increment capability, last value is remembered
alter table `users` modify column id INT NOT NULL AUTO_INCREMENT;
If you run the following command :
ALTER TABLE users ADD id int NOT NULL AUTO_INCREMENT PRIMARY KEY;
This will show you the error :
ERROR 1060 (42S21): Duplicate column name 'id'
This is because this command will try to add the new column named id to the existing table.
To modify the existing column you have to use the following command :
ALTER TABLE users MODIFY id int NOT NULL AUTO_INCREMENT PRIMARY KEY;
This should work for changing the existing column constraint....!
Delete the primary key of a table if it exists:
ALTER TABLE `tableName` DROP PRIMARY KEY;
Adding an auto-increment column to a table :
ALTER TABLE `tableName` ADD `Column_name` INT PRIMARY KEY AUTO_INCREMENT;
Modify the column which we want to consider as the primary key:
alter table `tableName` modify column `Column_name` INT NOT NULL AUTO_INCREMENT PRIMARY KEY;
Just change the ADD to MODIFY and it will works !
Replace
ALTER TABLE users ADD id int NOT NULL AUTO_INCREMENT
To
ALTER TABLE users MODIFY id int NOT NULL AUTO_INCREMENT;
Drop the primary index from the table:
ALTER TABLE `tableName` DROP INDEX `PRIMARY`;
Then add the id column (without a primary index). I have used a big int because I am going to have lots of data but INT(11) should work just as well:
ALTER TABLE `tableName` ADD COLUMN `id` BIGINT(11) NOT NULL FIRST;
Then modify the column with auto-increment (thanks php). It needs to be a primary key:
ALTER TABLE `tableName ` MODIFY COLUMN `id` BIGINT(11) UNSIGNED PRIMARY KEY AUTO_INCREMENT;
I have just tried this on a table of mine and it appears to have worked.
ALTER TABLE users CHANGE id int( 30 ) NOT NULL AUTO_INCREMENT
the integer parameter is based on my default sql setting
have a nice day
ALTER TABLE users ADD id int NOT NULL AUTO_INCREMENT primary key FIRST
For PostgreSQL you have to use SERIAL instead of auto_increment.
ALTER TABLE your_table_name ADD COLUMN id SERIAL NOT NULL PRIMARY KEY
ALTER TABLE `table` ADD `id` INT NOT NULL AUTO_INCREMENT unique
Try this. No need to drop your primary key.
This SQL request works for me :
ALTER TABLE users
CHANGE COLUMN `id` `id` INT(11) NOT NULL AUTO_INCREMENT ;
If you want to add an id with a primary key and identity:
ALTER TABLE user ADD id INT NOT NULL AUTO_INCREMENT FIRST , ADD PRIMARY KEY (id);
Check for already existing primary key with different column. If yes, drop the primary key using:
ALTER TABLE Table1
DROP CONSTRAINT PK_Table1_Col1
GO
and then write your query as it is.
Proceed like that :
Make a dump of your database first
Remove the primary key like that
ALTER TABLE yourtable DROP PRIMARY KEY
Add the new column like that
ALTER TABLE yourtable add column Id INT NOT NULL AUTO_INCREMENT FIRST, ADD primary KEY Id(Id)
The table will be looked and the AutoInc updated.
When I create a table and want to judge whether primary key is disabled,
rsColumns = meta.getPrimaryKeys(null, owner, tableName);
I can not see any info related to this, please give some help, thanks.
CREATE TABLE PKEY_TB3 (
INT_C1 INT PRIMARY KEY DISABLE,
VCHAR_C2 VARCHAR2(30) CONSTRAINT COL2_NAME_NN NOT NULL,
VCHAR_C3 VARCHAR2(30));
I want to add the database from my jform and there's a column which will be auto incremented, like when i click done, the data will be inserted and a column receipt_no will have a value 1. Next time I click done then this value should be 2 and so on.
So the problem is, i have created a table with receipt_no as the primary key and auto increment, so what should be my query in java, to add the data correctly in the table.
String sql = "insert into table_name values('"++"',...)";
Can you help me in this query?
Step 1: Creating table in MySQL
CREATE TABLE `user_master` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`Firstname` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Step 2: Insert record
INSERT INTO user_master (`Firstname`) values('Vicky');
Step 3: Fetch record
SELECT * FROM user_master;
I can't comment so there is an answer to the comment you posted in your question:
If your table is
CREATE TABLE users(
id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
firstname VARCHAR(25) NOT NULL,
lastname VARCHAR(25) NOT NULL,
);
You can simply auto_increment the primary by not giving it on your SQL request:
INSERT INTO users(firstname, lastname) VALUES('Steve', 'Jobs');
Java don't have to generate auto increment, it is SQL job :)
I'm new in sql. I have doubt. Let's say that I have two tables. One is called user and the other order.
User
User_Id - name - email
Order
Order_id - product - User_id
What query should I use to insert a new order in the order table with the User_id field related to the User_id from the user table(an existing user)
Eg:
Order_id - product - User_id
1a - plate - 1
2a - car - 3
3a - bike - 1
If you have name or email of the user, you can try this. If USER has a composite primary key on user_id and name columns, it will work without any issues. Better to keep foreign key relationship on user_id column of ORDER also.
Example has NAME column, you can try with email column also.
INSERT INTO ORDER (ORDER_ID, PRODUCT, USER_ID)
VALUES (1a, 'plate', (SELECT USER_ID FROM USER WHERE NAME = 'Existing user'));
EDIT:
I have worked on Oracle sql only. After your comment, found this link.
http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
If you have defined AUTO_INCREMENT on order_id column, you don't need to pass value.
INSERT INTO ORDER (PRODUCT, USER_ID)
VALUES ('plate', (SELECT USER_ID FROM USER WHERE NAME = 'Existing user'));
you use the standard sql insert.
insert into Order (Order_id, product, User_id) values ("3a", "bike", 1)
If your tables are set up property, there will be a foreign key restriction on the User_id field, so if you try to insert an order but don't reference a valid person, mysql will throw an error.
INSERT order (Order_id, product, User_id) VALUES (1a,plate,1)
The foreign key has nothing to do with the sql used in the insert it should have been set up when the table was created or via an ALTER TABLE query after it was created.
Relationships between tables are defined when you create the table, using the FOREIGN KEY.
CREATE TABLE Users(
UserId int primary key
);
CREATE TABLE Orders(
OrderId int primary key,
UserId int FOREIGN KEY REFERENCES Users(UserId)
);
Then you do a simple insert like:
INSERT INTO ORDER(OrderId, UserId) VALUES(1, 5);
Take a look at the documentation for foreign key constraints here: http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html.