How can i manually insert values if not exist...i tried following code but it produce error.How can i insert values if not exist in the table
String sql1 = "CREATE TABLE IF NOT EXISTS admin " +
"(id INTEGER not NULL AUTO_INCREMENT, " +
" user_name VARCHAR(255), " +
" password VARCHAR(255), " +
" isAdmin BOOLEAN NOT NULL DEFAULT '0', " +
" memo VARCHAR(255), " +
" PRIMARY KEY ( id ))";
stmt.executeUpdate(sql1);
String insert="INSERT INTO admin IF NOT EXISTS(id,user_name,password,isAdmin,memo)VALUES(1,'admin','admin',1,'memo')";
stmt.executeUpdate(insert);
it produce an error like
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF NOT EXISTS(id,user_name,password,isAdmin,memo)VALUES(1,'admin','admin',1,'mem' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
String insert="INSERT INTO admin IF NOT EXISTS(id,user_name,password,isAdmin,memo)VALUES(1,'admin','admin',1,'memo')";
should be
String insert="INSERT IGNORE INTO admin (id,user_name,password,isAdmin,memo)VALUES(1,'admin','admin',1,'memo')";
MySQL (and any other SQL implementation as well) doesn't support IF NOT EXISTS in INSERT queries.
your INSERT query must be
"INSERT IGNORE INTO admin (id,user_name,password,isAdmin,memo) VALUES (1,'admin','admin',1,'memo')"
What you want may be INSERT ... ON DUPLICATE KEY UPDATE or INSERT IGNORE....
The former will update an existing row if a duplicate insert is detected, while the latter will just throw away duplicate inserts.
In both cases, you'll have to create a UNIQUE constraint on the column you want to check for duplicates. If the UNIQUE is violated, the alternate function is invoked.
Related
I'm using JDBC in eclipse IDE , i want to put two foreign keys in my table 3 , one is referencing to the primary key in table 1 and one is referencing to the primary key in table 2. When i only put one foreign key constrains for any referencing table1 or table 2 , it works fine but when i include two it gives me sql exception as stated below:
java.sql.SQLSyntaxErrorException: You have an error in your SQL
syntax; check the manual that corresponds to your MySQL server version
for the right syntax to use near 'foreign key(T2) references
Table2(T2) )' at line 1
String createString =
// TABLE 1
"CREATE TABLE " + this.tableName + " ( " +
"T1 varchar(50) NOT NULL PRIMARY KEY )";
// TABLE 2
"CREATE TABLE " + this.tableName + " ( " +`enter code here`
"T2 varchar(50) NOT NULL PRIMARY KEY )";
// TABLE 3
"CREATE TABLE " + this.tableName + " ( " +
"T1 varchar(50) " +
"T2 varchar(50) " +
"foreign key(T1) references Table1 (T1)" +
"foreign key(T2) references Table2(T2) )";
First, this is actually a MySQL question, unrelated to Java/JDBC. Secondly, and more importantly, you don't appear to be using the correct syntax, which would be...
CREATE TABLE TableName (
T1 varchar(50),
T2 varchar(50),
foreign key(T1) references Table1(T1),
foreign key(T2) references Table2(T2)
);
Formatted for your code, it would look like this:
String createString = "CREATE TABLE " + this.tableName + " ( " +
" T1 varchar(50)," +
" T2 varchar(50)," +
" foreign key(T1) references Table1(T1)," +
" foreign key(T2) references Table2(T2));";
You were missing commas after each item in the items list for your CREATE TABLE statement.
Go easy on me, middle school teacher taking a CS class. I've got a Java program that asks for user name, height, weight, does some calculations and gives results to the user. I now need to store this data in a database. I can get the data to store until I start using primary and foreign keys.
Here is the error I can't figure out:
Error: java.sql.SQLIntegrityConstraintViolationException: The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'SQL180429151131780' defined on 'USERPROFILE'.
Here is my table:
drop table stayfitapp.userdata;
drop table stayfitapp.userprofile;
drop schema stayfitapp restrict;
create schema stayfitapp;
create table stayfitapp.userprofile
(
profileName varchar(255) not null primary key,
profileGender varchar(255) not null
);
create table stayfitapp.userdata
(
profileAge double not null,
profileWeight double not null,
profileHeight double not null,
profileWaistCircumference double not null,
profileHipCircumference double not null,
profileName varchar(255),
foreign key (profileName) references stayfitapp.userprofile(profileName)
);
Here is the section of the "app" that writes to the table...
public void save(){
try {
String query = "insert into stayfitapp.userprofile" + "(profileName, profileGender)" + "values" + "(?,?)";
String query2 = "insert into stayfitapp.userdata" + "(profileAge, profileWeight, profileHeight, profileWaistCircumference, profileHipCircumference)" + "values" + "(?,?,?,?,?)";
Connection myConnection = DriverManager.getConnection("jdbc:derby://localhost:1527/stayfitDB2", "username", "password");
Statement myStatement = myConnection.createStatement();
//Statement myStatement2 = myConnection.createStatement();
PreparedStatement prepared = myConnection.prepareStatement(query);
prepared.setString(1, profileName);
prepared.setString(2, profileGender);
PreparedStatement prepared2 = myConnection.prepareStatement(query2);
prepared2.setDouble(1, profileAge);
prepared2.setDouble(2, profileWeight);
prepared2.setDouble(3, profileHeight);
prepared2.setDouble(4, profileWaistCircumference);
prepared2.setDouble(5, profileHipCircumference);
int rowsAffected = prepared.executeUpdate();
int rowsAffected2 = prepared2.executeUpdate();
if(rowsAffected==0)
{
System.out.println("Warning: User data did not save!");
}
else
{
System.out.println("User info saved!");
}
}
catch(SQLException e)
{
System.out.println("Error: "+e.toString());
}
Your save() method will attempt to add the user to the stayfitapp.userprofile table. This table has a field called profileName. profileName is the "primary key" so no duplicate values are allowed.
The error that you are getting is saying that you cannot add(insert) the record to the table because the table already has a record with the same name.
Does your program work okay if you use a different name each time?
You will need to add some logic to your program to deal with the scenario where the profileName already exists in the table. This will probably involve deleting or updating the existing record.
This is the problem.
insert into stayfitapp.userprofile"
+ "(profileName, profileGender)" + "values" , etc
You have nothing to check to see if a record already exists. Something like this would work better.
insert into stayfitapp.userprofile
profileName, profileGender
select distinct ?, ?
from someSmallTable
where not exists (
select 1
from stayfitapp.userprofile
where profileName = ?
)
The someSmallTable bit depends on your database engine, which you didn't specify.
I ended up writing a method to check if the username was already in the profile table. If the username was a duplicate I only wrote to the data table. If the username was new I wrote to both tables.
Thank you for your help! I'm sure there was a more efficient method (figuratively and literally) but I'm on to my final project and nearly surviving an actual CS class.
I created a sequence and I want a table to make use of it. The creation of the sequence works fine. However, I when I try to alter the table in order to make use of the sequence, I get this error (in personInformationSequenceAlterTest):
ORA-00940: invalid ALTER command
Please note I need to use Java (Eclipse IDE).
String personInformationSequenceTest =
"CREATE SEQUENCE seq_person "
+ "start with 1 "
+ "increment by 1 "
+ "NOCACHE "
+ "NOCYCLE ";
String personInformationSequenceAlterTest =
"alter table personInformationTest "
+ "alter column personId "
+ "set default nextval('seq_person')";
String personInformationSequenceOwnedTest =
"alter sequence seq_person owned by personInformationTest.personId";
Your alter statement has syntax problem.
Try this (assuming datatype is int for that column. Change accordingly):
alter table personInformationTest modify (personId int default seq_person.nextval);
This will only work in Oracle 12c and up.
For 11g or lower, you can use triggers. If you don't want to use triggers, you can explicitly use seq_person.nextval in your inserts.
insert into personInformationTest (personId, . . .)
values (seq_person.nextval, . . .)
Check by Changing
String personInformationSequenceAlterTest =
"alter table personInformationTest "
+ "alter column personId "
+ "set default nextval('seq_person')";
to
String personInformationSequenceAlterTest =
"alter table personInformationTest "
+ "modify column personId "
+ "set default nextval('seq_person')";
In Oracle and MySql we use "Modify" for altering an existing column . In SQL Server / MS Access , "Alter" is used .
I am getting the following error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'userId' in 'field list'
The code which is causing this error is this:
PreparedStatement pstmt =
con.prepareStatement(
"INSERT INTO " +
tableName +
" (userId,username,email,password) VALUES (?,?,?,?)");
My table gets created by the following command
stmt.executeUpdate(
"CREATE TABLE " +
tableName +
" (" +
" userId INT, " +
" userName VARCHAR(255) NOT NULL, " +
" email VARCHAR(255) NOT NULL, " +
" password VARCHAR(255), " +
" PRIMARY KEY(userId)" +
" )");
stmt.close();
Can someone help me spot my mistakes if any. I am a novice in this so I am kind of struggling to find where exactly the error is.
The error was because there already existed another table with the same table name.
One other thing to look at is triggers. I was getting the same error and eventually determined that the error was the result of a trigger statement rather than the insert statement. The "unknown column" was in a table the trigger was trying to insert into.
If you are using insert statement and there is column value missing or empty. It can give this error. I was using prepared statement. I got this error for a column having numeric data type. The root cause of this was empty string being passed as column value. Strangely it throws "unknown column" e
I have a fragment of code in Java which inserts data into my database.
I was advised to put AUTO_INCREMENT and give each row a unique number.
But it now gives me an error:
java.sql.SQLException: Incorrect integer value: 'DEFAULT' for column
'usersID' at row 1
I assume this is because it's casting the AUTO_INCREMENT value into a string?
How do I get around this as it's not my java program that creates the unique number, but the database itself.
pst.setString(1, "DEFAULT");
String query_to_update = "INSERT INTO `evidence_db`.`mcases` ("
+ "`PID`,"
+ "`Name`) "
+ "VALUES (?,?);";
pst.setInt(1, 0);
Above was the line that I needed. Thanks to all that tried to be helpful.