My java model is causing these warnings in my logs...
WARNING: PER01000: Got SQLException executing statement "CREATE TABLE users (id INTEGER GENERATED BY DEFAULT AS IDENTITY NOT NULL, last_login TIMESTAMP, name VARCHAR(255), PRIMARY KEY (id))": java.sql.SQLException: Table/View 'USERS' already exists in Schema 'APP'.
WARNING: PER01000: Got SQLException executing statement "CREATE TABLE GUEST (ID BIGINT NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID))": java.sql.SQLException: Table/View 'GUEST' already exists in Schema 'APP'.
WARNING: PER01000: Got SQLException executing statement "CREATE TABLE content (id INTEGER GENERATED BY DEFAULT AS IDENTITY NOT NULL, body CLOB(2147483647), user_id INTEGER, PRIMARY KEY (id))": java.sql.SQLException: Table/View 'CONTENT' already exists in Schema 'APP'.
WARNING: PER01000: Got SQLException executing statement "CREATE TABLE SEQUENCE (SEQ_NAME VARCHAR(50) NOT NULL, SEQ_COUNT DECIMAL(15), PRIMARY KEY (SEQ_NAME))": java.sql.SQLException: Table/View 'SEQUENCE' already exists in Schema 'APP'.
WARNING: PER01000: Got SQLException executing statement "INSERT INTO SEQUENCE(SEQ_NAME, SEQ_COUNT) values ('SEQ_GEN', 0)": 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 'SQL111211163034730' defined on 'SEQUENCE'.
I actually have a couple of questions here...
users and content tables I created already, and used Netbeans to generate my models.
How come it's trying to create the tables when the models were created from the tables?
Secondly, I have no idea where sequence is coming from?
Related
I just managed to connect with a local .accdb Access Database and am now trying to create my tables. I run these two lines with Java and there are no errors during running these SQL-Commands:
Statement st = d.createStatement();
st.executeUpdate("CREATE TABLE suppliers ( [name] TEXT(255), [adress] TEXT(255), [ID] AUTOINCREMENT PRIMARY KEY);");
st.executeUpdate("CREATE TABLE quality ( [name] TEXT(255) );");
st.close();
But now as I want to open the just created tables with Microsoft Access there is a difference between the two generated tables.
I can open the table "quality" normally and insert some values.
Now if I'm trying to open "suppliers" I get this error message:
It is in German and means "The database '' could not been opened. Either the database doesn't get recognized by your application or the file is damaged."
So I tried to remove the "[ID] AUTOINCREMENT PRIMARY KEY" and it works fine without this. So the error must be caused by the "AUTOINCREMENT".
To connect with the database I use ucanacess:
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
c = DriverManager.getConnection("jdbc:ucanaccess://C:/bin/Test.accdb");
Have I done something wrong with my "AUTOINCREMENT"?
I am able to reproduce your issue with UCanAccess 4.0.2. It appears to be related to the [ID] column being specified last. That is, this causes the issue:
sql = "CREATE TABLE suppliers ( [name] TEXT(255), [adress] TEXT(255), [ID] AUTOINCREMENT PRIMARY KEY)";
... but specifying the columns in this order works okay:
sql = "CREATE TABLE suppliers ([ID] AUTOINCREMENT PRIMARY KEY, [name] TEXT(255), [adress] TEXT(255))";
I will pass this information along to the UCanAccess development team.
I have an application which starts (AppStarter) a web server with a web application. The Web Application has migration scripts (flyway).
I want to write some data from AppStarter through JDBC in a table. But I want to create the table if it does not exist. The table also has some constraints.
Within the AppStarter I execute following command:
CREATE CACHED TABLE PUBLIC.CORE_USERROLE_TO_PARAMETER (
ID VARCHAR(32) PRIMARY KEY NOT NULL,
VERSION INTEGER,
USER_ID VARCHAR(32)NOT NULL,
ROLE_ID VARCHAR(32) NOT NULL,
PARAMETER VARCHAR(255) NOT NULL
);
ALTER TABLE PUBLIC.CORE_USERROLE_TO_PARAMETER ADD CONSTRAINT PUBLIC.CURTBP_USER_ID FOREIGN KEY(USER_ID) REFERENCES PUBLIC.CORE_USER(ID) NOCHECK;
ALTER TABLE PUBLIC.CORE_USERROLE_TO_PARAMETER ADD CONSTRAINT PUBLIC.CURTBP_ROLE_ID FOREIGN KEY(ROLE_ID) REFERENCES PUBLIC.CORE_USER_ROLE(ID) NOCHECK;
The web app also reads some information from this table and creates the tables.
Now I have a sql migration script
CREATE CACHED TABLE IF NOT EXISTS PUBLIC.CORE_USERROLE_TO_PARAMETER (
ID VARCHAR(32) PRIMARY KEY NOT NULL,
VERSION INTEGER,
USER_ID VARCHAR(32)NOT NULL,
ROLE_ID VARCHAR(32) NOT NULL,
PARAMETER VARCHAR(255) NOT NULL
);
But how do I create the constraint only if they does not already exist?
Thanks in advance
Currently I can get if the constraints exists with
select * from INFORMATION_SCHEMA.CONSTRAINTS WHERE CONSTRAINT_NAME='CURTRP_USER_ID'
but how do I build this into a if query with H2
Edit:
I could move the constraint part in total to the migration script, but this seems somehow wrong.
I am working with H2 Database.
Following my comment, this should be possible:
ALTER TABLE PUBLIC.CORE_USERROLE_TO_PARAMETER
ADD CONSTRAINT IF NOT EXISTS PUBLIC.CURTBP_USER_ID
FOREIGN KEY(USER_ID) REFERENCES PUBLIC.CORE_USER(ID) NOCHECK;
ALTER TABLE PUBLIC.CORE_USERROLE_TO_PARAMETER
ADD CONSTRAINT IF NOT EXISTS PUBLIC.CURTBP_ROLE_ID
FOREIGN KEY(ROLE_ID) REFERENCES PUBLIC.CORE_USER_ROLE(ID) NOCHECK;
Use this query to get the foreign key constraints
SELECT * FROM INFORMATION_SCHEMA.CONSTRAINTS WHERE CONSTRAINT_TYPE = 'REFERENTIAL'
You can try ALTER TABLE IF EXISTS like CREATE IF EXISTS. If its a responsibility of your application only, and not handled by another app or script.
I am new in derby library. why I got this error when I use the auto_increment in my query?
here is my java code
this.conn.createStatement().execute(create table user("user_id int auto_increment, PRIMARY KEY(user_id))");
I tried this in mysql server and its works but in derby I got this error
java.sql.SQLSyntaxErrorException: Syntax error: Encountered "auto_increment" at line 1
why I got this error?
Derby does not have auto_increment as a keyword. In derby you need to use identity columns to implement auto increment behaviour
For example
CREATE TABLE students
(
id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
name VARCHAR(24) NOT NULL,
address VARCHAR(1024),
CONSTRAINT primary_key PRIMARY KEY (id)
) ;
Above statement will create Student table with id as auto increment column and primary key as well.
Hope this helps
I want to create a method to dynamically create tables just passing the table name as a variable.
I have defined my xml mapper
<mapper namespace="com.mappers.TableCreatorMapper">
<cache />
<insert id="createNewTableIfNotExists" parameterType="String" >
CREATE TABLE IF NOT EXISTS #{tableName}
(
`ID` varchar(20) NOT NULL,
PRIMARY KEY (`ID`)
)
ENGINE=InnoDB
</insert>
</mapper>
And my Java Interface Mapper is simply:
public interface TableCreatorMapper {
public void createNewTableIfNotExists(String tableName);
}
but when I call my interface
tableCreatorMapper.createNewTableIfNotExists("test");
I get the following exception:
org.springframework.jdbc.BadSqlGrammarException:
### Error updating database. Cause: 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 ''test'
(
`ID` varchar(20) NOT NULL,
PRIMARY KEY (`ID`)
' at line 1
### The error may involve com.mappers.TableCreatorMapper.createNewTableIfNotExists-Inline
### The error occurred while setting parameters
### SQL: CREATE TABLE IF NOT EXISTS ? ( `ID` varchar(20) NOT NULL, PRIMARY KEY (`ID`) ) ENGINE=InnoDB
### Cause: 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 ''test'
(
`ID` varchar(20) NOT NULL,
PRIMARY KEY (`ID`)
' at line 1
; bad SQL grammar []; nested exception is 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 ''test'
(
`ID` varchar(20) NOT NULL,
PRIMARY KEY (`ID`)
' at line 1
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:231)
at org.sp
If I instead change the query adding the ``for the table name:
CREATE TABLE IF NOT EXISTS `#{tableName}`(
`ID` varchar(20) NOT NULL,
PRIMARY KEY (`ID`)
)
ENGINE=InnoDB
I get
### The error occurred while setting parameters
### SQL: CREATE TABLE IF NOT EXISTS `?`( `ID` varchar(20) NOT NULL, PRIMARY KEY (`ID`) ) ENGINE=InnoDB
### Cause: java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
; SQL []; Parameter index out of range (1 > number of parameters, which is 0).; nested exception is java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
Any idea why?
try
CREATE TABLE IF NOT EXISTS ${_parameter}
(
`ID` varchar(20) NOT NULL,
PRIMARY KEY (`ID`)
)
ENGINE=InnoDB
#{name} is for parameters in PreparedStatement (see String Substitution in Parameters).
in DAO, use annotation #Param
void createTableIfNotExist(#Param("uuid") String uuid);
in MAPPER, use $
<update id="createTableIfNotExist" parameterType="java.lang.String">
CREATE TABLE IF NOT EXISTS `table_${uuid}`
(
`id` bigint(18) NOT NULL,
`info` varchar(18) NOT NULL,
PRIMARY KEY (`id`)
)
ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='this table is generated by java code.'
</update>
<bind> could be used in MAPPER too.
I am getting error in this: prepared statement.
Prepared Statement:
PreparedStatement pStatement=connection.prepareStatement
("CREATE TABLE `details`.?(`ID` VARCHAR(255) NOT NULL,`Score` VARCHAR(255) NULL);
INSERT INTO `testdetails`.? (`ID`) VALUES (?);");
pStatement.setString(1, "usrname");
pStatement.setString(2, "usrname");
pStatement.setString(3, "001");
pStatement.executeUpdate();
Error details:
Severe: 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
''usrname'(`ID` VARCHAR(255) NOT NULL,`Score` VARCHAR(255) NULL);INSER' at line 1
How to fix this error?
JDBC parameters aren't usually usable for table and column names - they're only for values.
Unfortunately, I think this is one of those cases where you will need to be build the SQL dynamically. You will want to be very careful about which values you allow, of course.
This error appears because, you use #setString, and the string gets wrapped by ''.
To fix this, you can use one of this snippets:
"CREATE TABLE `details`.#tableName#(`ID` VARCHAR(255) NOT NULL,`Score` VARCHAR(255) NULL); INTO `testdetails`.#tableName# (`ID`) VALUES (?);".replaceAll("#tableName#", "usrname");
or
new StringBuilder("CREATE TABLE `details`.").append("usrname").append("(`ID` VARCHAR(255) NOT NULL,`Score` VARCHAR(255) NULL); INTO `testdetails`.").append("usrname").append("(`ID`) VALUES (?);").toString();
and pass resulted string into #prepareStatement() method.