I am trying to create a text table set its values from a file and then insert these values back into a normal table using hsqldb in a Java code as shown in this code:
String sqlkeywordcreate=new String ("CREATE TABLE keywordsTable " + " (k_id INTEGER IDENTITY not NULL PRIMARY KEY, keywords varchar(20))");
String sqlkeywordcreate1=new String ("CREATE TEXT TABLE tempKeywordsTable " + " (key varchar(20))");
System.out.println(sqlkeywordcreate);
stmt1.executeUpdate(sqlkeywordcreate);
stmt1.executeUpdate(sqlkeywordcreate1);
int numOfFields=di.getAllTerms();
String setTempKeywordsTable= new String ("set table "+ "tempKeywordsTable"+ " source 'E:/Thesis/ThesisWork/outdata/keywords.txt';ignore_first=false;shutdown=true");
stmt1.execute( setTempKeywordsTable);
String insertkey= new String("INSERT INTO keywordsTable"+ "(keywords)"+ "select key from tempKeywordsTable");
stmt1.executeUpdate(insertkey);
String dropTempKey= new String("drop table tempKeywordsTable");
stmt1.executeUpdate(dropTempKey);
But when I run this I got this exception:
java.sql.SQLException: bad TEXT table source file - line number: 0 org.hsqldb.HsqlException: Access is denied: E:/Thesis/ThesisWork/outdata/keywords.txt in statement [set table tempKeywordsTable source 'E:/Thesis/ThesisWork/outdata/keywords.txt']
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.fetchResult(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.executeUpdate(Unknown Source)
at ThesisCode.ReductionTry.main(ReductionTry.java:73)
Exception in thread "main" java.lang.NullPointerException
at ThesisCode.ReductionTry.main(ReductionTry.java:147)
I searched a lot to figure out the problem but I could not find anything.
Please give me some advice.
Watch out for the spaces when concatenating strings, you should write:
String setTempKeywordsTable= new String ("set table "+"tempKeywordsTable"+ " source 'E:/Thesis/ThesisWork/outdata/keywords.
instead of:
String setTempKeywordsTable= new String ("set table"+ "tempKeywordsTable"+ " source 'E:/Thesis/ThesisWork/outdata/keywords.
You're doing the same mistake in String insertkey.
One update from me:
Now we must use relative path. For example: db exist here: "c:\folder1\folder2". And file with data should be in folder2 or in child folders.
Related
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 trying to transfer data from a text table to a normal table, where the data is taken originally from a txt file.
I am using hsqldb
This is what I did. I have no error or exception , but both the tables are empty.
String sqlkeywordcreate=new String ("CREATE TABLE keywordsTable " + " (k_id INTEGER IDENTITY not NULL PRIMARY KEY, keywords varchar(20))");
String sqlkeywordcreate1=new String ("CREATE TEXT TABLE tempKeywordsTable " + " (key varchar(20))");
stmt1.executeUpdate(sqlkeywordcreate);
stmt1.executeUpdate(sqlkeywordcreate1);
int numOfFields=di.getAllTerms();
String setTempKeywordsTable= new String ("set table "+"tempKeywordsTable"+ " source 'keywords.txt'");
//System.out.print(setTempKeywordsTable);
stmt1.executeUpdate( setTempKeywordsTable);
String insertkey= new String("INSERT INTO keywordsTable "+"(keywords)"+ " select key from tempKeywordsTable");
stmt1.executeUpdate(insertkey);
String dropTempKey= new String("drop table tempKeywordsTable");
//stmt1.executeUpdate(dropTempKey);
String sqlcreate=new String("CREATE TABLE "+ tableName +" (id INTEGER IDENTITY not NULL PRIMARY KEY)");
String sqlselect=new String("select k_id from keywordsTable");
Please guide me and give me ideas to solve this issue.
Thanks
The code looks correct. You should add a test count after the line with "set table tempKeywordsTable source " to make sure the data is linked properly to the TEXT table. If there is data, the rest will work.
A possible cause of your code not working is the path of the keywords.txt file. This file should be in the same directory as the rest of the database files.
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.
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.