Creating a sequence on an existing table - ORA-00940: invalid ALTER command - java

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 .

Related

I cant create h2 database before tests, but after first test other tests work fine

i am trying to make my tests on h2 database. But my first test always falling with error
nested exception is io.r2dbc.spi.R2dbcBadGrammarException: [90079] [90079] Schema "DEF" not found; SQL statement:
although other tests for fine.
For making database i use #BeforeEach annotation
here code:
String sql =
/*"DROP SCHEMA DEF;\n" +*/
"CREATE SCHEMA IF NOT EXISTS DEF; \n " +
"CREATE TABLE IF NOT EXISTS def.definition ();\n" +
"ALTER TABLE def.definition ADD COLUMN IF NOT EXISTS id varchar NOT NULL ;\n" +
"ALTER TABLE def.definition ADD COLUMN IF NOT EXISTS path varchar NOT NULL default NULL;\n" +
"ALTER TABLE def.definition ADD COLUMN IF NOT EXISTS name varchar NULL;\n" +
"ALTER TABLE def.definition ADD COLUMN IF NOT EXISTS description varchar NULL;\n" +
"ALTER TABLE def.definition ADD COLUMN IF NOT EXISTS type varchar NULL;\n" +
"ALTER TABLE def.definition ADD COLUMN IF NOT EXISTS \"schema\" json NULL;\n" +
"ALTER TABLE def.definition ADD CONSTRAINT IF NOT EXISTS definition_pk PRIMARY KEY (id);\n" +
"ALTER TABLE def.definition ADD CONSTRAINT IF NOT EXISTS definition_un UNIQUE (path);\n" +
"CREATE INDEX IF NOT EXISTS definition_name_idx ON def.definition (name);\n" +
"CREATE INDEX IF NOT EXISTS definition_description_idx ON def.definition (description);";
Mono<Integer> integerMono = databaseClient.sql(sql)
.fetch()
.rowsUpdated();
StepVerifier.create(integerMono)
.expectNextCount(1)
.verifyComplete();
I tried rewriting sql code, or using another sql dialect
After some research i found new way of executing sql before tests:
Mono.from(connectionFactory.create())
.map(
c -> {
ScriptUtils.executeSqlScript(c, new ClassPathResource("scripts/create.sql"))
.subscribe();
return "123";
})
.subscribe();
Here u create connection from your connection factory, then using sql file(in my case it is create.sql at scripts package at resources),execute your sql script

How can I create a Table with two Foreign Key References to one other Table via UCanAccess?

To build the References direct in MS-Access is no Problem.
To do it with UCanAccess results in a "net.ucanaccess.jdbc.UcanaccessSQLException:...".
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection connection = DriverManager.getConnection("jdbc:ucanaccess://e:/TestDB.accdb;memory=true");
Statement statement = connection.createStatement();
//
String tableToBeReferenced = "PersonsTable";
String tableWithTheReferences = "RelationShipsTable";
try {// Tidy up
statement.execute("DROP TABLE " + tableWithTheReferences);
} catch (Exception exeption) {}
try {// Tidy up
statement.execute("DROP TABLE " + tableToBeReferenced);
} catch (Exception exeption) {}
statement.execute("CREATE TABLE " + tableToBeReferenced + "(ID autoincrement NOT NULL PRIMARY KEY,"//
+ "Name VARCHAR(255)"//
+ ")");
statement.execute("CREATE TABLE " + tableWithTheReferences + "(ID LONG NOT NULL PRIMARY KEY,"//
+ "RelationShip VARCHAR(255) NOT NULL DEFAULT 'FRIENDS',"//
+ "Person1Id LONG NOT NULL,"//
+ "Person2Id LONG NOT NULL)");
// reference #1
statement.execute("ALTER TABLE " + tableWithTheReferences + //
" ADD CONSTRAINT FOREIGN_KEY_1 FOREIGN KEY (Person1Id) REFERENCES " //
+ tableToBeReferenced + "(ID) ON DELETE CASCADE");
// reference #2
statement.execute("ALTER TABLE " + tableWithTheReferences + //
" ADD CONSTRAINT FOREIGN_KEY_2 FOREIGN KEY (Person2Id) REFERENCES " //
+ tableToBeReferenced + "(ID) ON DELETE CASCADE");
If I create only the first Reference it works.
If I create only the second Reference it works.
But when I try to build both References it fails.
I am able to reproduce the issue under UCanAccess 4.0.3. Neither HSQLDB nor Jackcess has a problem with creating two independent FK relationships between the same two tables, so it looks like it might be a bug in UCanAccess. I will report the issue to the UCanAccess development team and update this answer with any news.
Update:
A fix for this issue has been implemented and will be included in the UCanAccess 4.0.4 release.
I think it will not work since you have "ON DELETE CASCADE" for both your foreign keys.

SQL Insert Into a newly created column ,data placed after the last row of the previous column

I have a problem with a SQL statement. I have a java app with a button to add a column into a database. For every new date, I have a new column created, which is done using the following query
final String queryCreate = "alter table Currency add '"+ newColumn + "' decimal ";
When I try to populate the column with data using the following query:
final String queryAdd = "insert into Currency( '" + newColumn + "' ) values(1.95583)";
The data is added below the last row of the previous column.
like this:
https://postimg.org/image/579gjmyzj/
My question is why the insert statement does what it does in my situation, what am I doing wrong?
INSERT creates new records, if you want to modify existing records you need to use UPDATE.
For example, to modify the first record:
"UPDATE Currency SET " + newColumn + " = 1.95583 WHERE Currency_ID = 1"
use update query
assuming strCurrencyID="1";
strCurrencyName="EUR";
final String queryAddUpdate =
if exists(Select Top 1 1 from Currency where Currency_ID=" + strCurrencyID +")
Begin update Currency set " + newColumn + "=1.95583 where Currency_ID=" +strCurrencyID + "
End
Else
Begin
insert into Currency(Currency_id, Currency_name, '" + newColumn + "' ) values("+ strCurrencyID +",'" + strCurrencyName + ", 1.95583)
End"
This will update the value in in column if currency id exists if not this will insert new row.
But I think database design should be change can you explain your business requirement.

transfer data from text table to normal table hsqldb java

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.

Database value insertion Error

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.

Categories

Resources