Problem with create temporary table mysql in java program - java

I'm new on java programming.
I've a problem with creation a temporary table in Java..
Database db = new Database();
String query="create temporary table sconti (codcon int(11) not null, " +
" sigcos char(4) not null, codgru char(4) not null, codsgr char(4) not null, " +
" desgru char(100) not null, dessgr char(100) not null, sconto1 double(16,4) not null, " +
" sconto2 double(16,4) not null,sconto3 double(16,4) not null,primary key(codcon,sigcos,codgru,codsgr));";
db.executequery(query);
With first instruction I connect to the database then do the query with executequery
the debug error is:
Field 'codgru' doesn't have a default value

If you set a column as not null, you have to set a Default value. This is missing for some columns in query.
So remove not null or add a default value.
https://dev.mysql.com/doc/refman/8.0/en/create-table.html

Related

Why is sqlite auto_increment not incrementing?

I've got a database set up to store notes. I want to auto increment the first column. I've tried this, but when I read from the database every result in that column is 'null'.This is the code for creating the DB.
private static final String NOTES_TABLE_CREATE =
"CREATE TABLE " + NOTES_TABLE_NAME + " (" +
COLUMN_NAMES[0] + " INTEGER AUTO_INCREMENT, " +
COLUMN_NAMES[1] + " TEXT, " +
COLUMN_NAMES[2] + " TEXT, " +
COLUMN_NAMES[3] + " TEXT, " +
COLUMN_NAMES[4] + " TEXT, " +
COLUMN_NAMES[5] + " TEXT, " +
COLUMN_NAMES[6] + " TEXT);";
This is the code for getting the DB result.
SQLiteDatabase db = this.getReadableDatabase();
Cursor result = db.query(NOTES_TABLE_NAME, COLUMN_NAMES, null, null, null, null, null, null);
result.moveToFirst();
result.moveToNext();
System.out.println(result.getInt(0));
System.out.println(result.getString(1));
This is the output from logcat
04-09 17:56:17.981 22147-22147/com.example.a8460p.locationotes I/System.out: 0
04-09 17:56:17.981 22147-22147/com.example.a8460p.locationotes I/System.out: notetitle1234567890
AUTO_INCREMENT (as opposed to INTEGER PRIMARY KEY AUTOINCREMENT) is not supported in sqlite.
This is a little non-obvious, because sqlite silently ignores column constraints it does not recognize:
sqlite> CREATE TABLE test (
a INTEGER FABBELBABBEL NOT NULL
);
sqlite> .schema test
CREATE TABLE test (a INTEGER FABBELBABBEL NOT NULL);
sqlite> INSERT INTO test (a) VALUES (1);
sqlite> INSERT INTO test (a) VALUES (NULL);
Error: NOT NULL constraint failed: test.a
AUTOINCREMENT on the other hand, is supported for integer primary keys and only there, so the obvious workaround attempt is not supported, either:
sqlite> CREATE TABLE test (a INTEGER AUTOINCREMENT NOT NULL, b INTEGER);
Error: near "AUTOINCREMENT": syntax error
In short: Auto increment is only available for integer primary keys.

JDBC Auto Increment

I am trying to create table that has column that auto increments the user id column. When I use the below code I get this error:
Exception in thread "main" java.sql.SQLSyntaxErrorException: ORA-00907: missing right parenthesis
String sql = "CREATE TABLE DBUSER("
+ "USER_ID NUMBER(5) NOT NULL AUTO_INCREMENT, "
+ "USERNAME VARCHAR(20) NOT NULL, "
+ "CREATED_BY VARCHAR(20) NOT NULL, "
+ "CREATED_DATE DATE NOT NULL, " + "PRIMARY KEY (USER_ID) "
+ ")"; Statement stmt;
stmt = connection.createStatement();
stmt.executeUpdate(sql);
It should work if you remove the auto-increment
CREATE TABLE DBUSER(
USER_ID NUMBER(5) NOT NULL,
USERNAME VARCHAR(20) NOT NULL,
CREATED_BY VARCHAR(20) NOT NULL,
CREATED_DATE DATE NOT NULL,
PRIMARY KEY (USER_ID)
)
Auto increment is not supported in Oracle

Compare an SQL file to an existing database table with Java

I am writing a bit of Java (1.7) code to test a given database table against a given sql file. What I would like is a way to turn my sql file into a java object, then test the db field names and field types are the same as the file backed object.
An example sql file looks like this:
create table foo (
id int not null auto_increment,
term_id varchar(128) not null,
term_name varchar(255) not null,
parent_id varchar(128) not null,
parent_name varchar(255),
top_term_flag varchar(5),
primary key (id)
);
create index foo_pn on foo ( parent_name );
create index foo_ttf on foo ( top_term_flag );
And the part of my Java program to do this check looks like this:
// Step 1, confirm the table exists
// Database and table tests
DatabaseMetaData dbm = connection.getMetaData();
// check if "this.dbtable" exists.
// The ToUpperCase covers Oracle
ResultSet tables = dbm.getTables(null, null, this.dbtable.toUpperCase(), null);
if (tables.next()) {
// Table exists
log.info("Table: {} exists!", this.dbtable);
// Step 2, get each field and test against the file
ResultSet columns = dbm.getColumns(null, null, this.dbtable, null);
while ( columns.next()) {
String name = columns.getString(4); // this gets the column name
-> Now what? <-
}
}
I've looked at Spring JDBCTestUnit and Flyway, but they don't seem to provide the functionality I need.
Thank you.
Update:
I understand I can also use Hibernate to generate my Java classes that represent my sql file and then test the DB table against those. Does any one have a sample for how to get this done?
Using JSqlParser 0.8.8 from https://github.com/JSQLParser/JSqlParser.
Here is a parsing example to get column names, table name, types. As a result you get a hierarchy of java objects from your sqls.
public class CheckSQLs {
public static void main(String[] args) throws JSQLParserException {
String sqls = "create table foo (\n"
+ " id int not null auto_increment,\n"
+ " term_id varchar(128) not null,\n"
+ " term_name varchar(255) not null,\n"
+ " parent_id varchar(128) not null,\n"
+ " parent_name varchar(255),\n"
+ " top_term_flag varchar(5),\n"
+ " primary key (id)\n"
+ ");\n"
+ "create index foo_pn on foo( parent_name );\n"
+ "create index foo_ttf on foo ( top_term_flag );";
for (String sql : sqls.split(";")) {
Statement parse = CCJSqlParserUtil.parse(sql);
System.out.println(parse);
if (parse instanceof CreateTable) {
CreateTable ct = (CreateTable)parse;
System.out.println("table=" + ct.getTable().getFullyQualifiedName());
for (ColumnDefinition colDef : ct.getColumnDefinitions()) {
System.out.println("column=" + colDef.getColumnName() + " " + colDef.getColDataType() + " " + colDef.getColumnSpecStrings());
}
}
}
}
}
This runs with the output:
CREATE TABLE foo (id int not null auto_increment, term_id varchar (128) not null, term_name varchar (255) not null, parent_id varchar (128) not null, parent_name varchar (255), top_term_flag varchar (5), primary key (id))
table=foo
column=id int [not, null, auto_increment]
column=term_id varchar (128) [not, null]
column=term_name varchar (255) [not, null]
column=parent_id varchar (128) [not, null]
column=parent_name varchar (255) null
column=top_term_flag varchar (5) null
Now you could use this object to validate against your database.
If the SQL file syntax doesn't vary much from your example, you could write a simple parser to read the file and generate your java object: table plus list of fields/types and indexes
"tablename" always comes after "create table"
the field names and types always come after that
indexes after that
Or there are parsers available:
jsqlparser
http://jsqlparser.sourceforge.net/
Other questions on this site cover some of the same ground
SQL parser library for Java

Update table with primary key and unique columns using Hibernate and mySQL

I have a table containing four columns:
CREATE TABLE `participants` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(128) NOT NULL,
`function` VARCHAR(255) NOT NULL,
`contact` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `name_function_contact` (`name`, `function`, `contact`)
)
From the application I get participants-objects, which might have values for name, functionand contactwhich are already in that exact matter in the database. In this case I want Hibernate to get me the idof that object, otherwise I want to save the object.
Using saveOrUpdate()I just get an:
org.hibernate.exception.ConstraintViolationException: Duplicate entry 'NAME-FUNCTION-CONTACT: NAME' for key 'name_function_contact'
How can I accomplish this? Thanks a lot!
Since the answers suggested that Hibernate cannot do it on its own (bummer!) I solved it the "native sql" way:
Participants tempParti = ((Participants) session.createQuery("FROM Participants WHERE name = '" + p.getName() + "' AND function = '" + p.getFunction() + "' AND contact = '" + p.getContact() + "'").uniqueResult());
if (tempParti != null) {
p = tempParti;
} else {
session.save(p);
}
Works like a charm! Thanks to all of you!
I am no expert in Hibernate. But from Mysql perspective, you do the following.
use INSERT IGNORE INTO... to add the value in the table. If the number of rows inserted is 0, then you can manually get the ID of the row by a SELECT statement.
EDIT: LAST_INSERT_ID() was wrong here. I have edited the answer.

Why is my getColumnIndex() returning -1?

Ok, so here is my database create statement:
create table entry (
_id integer primary key autoincrement,
date integer not null,
checknum integer,
payee text not null,
amount integer not null,
category text,
memo text,
tag text
);
After the datbase is created, and I make a call like:
mChecknum = cursor.getColumnIndex("checknum");
mChecknum is -1. I have pulled the database from the device and used SQLite Browser on it, and the checknum field is there.
Block around statement in question:
mDbHelper.open();
Cursor cursor = mDbHelper.fetchAll();
startManagingCursor(cursor);
COL_DATE = cursor.getColumnIndex("date");
Log.v("Main:123", "COL_DATE: " + String.valueOf(COL_DATE) );
COL_CHECKNUM = cursor.getColumnIndex("checknum");
Log.v("Main:125", "COL_CHECKNUM: " + String.valueOf(COL_CHECKNUM) );
COL_PAYEE = cursor.getColumnIndex("payee");
COL_DATE returns 1 and COL_PAYEE returns 2. Why is COL_CHECKNUM being ignored/passed over?
In my situation getColumnIndex was returning error on the column which had name which contained the "." symbol i.e.:
int colIndex = cursor.getColumnIndex("Item No.");
and despite the column "Item No." was inside the cursor (the debugger Watch showed it) trying to get the column index failed.
In my fetch/fetchAll database functions, I forgot to update the query with the new column.
For example, before i added the new column, my fetchAll code looked like:
public Cursor fetchAll() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_DATE,
KEY_PAYEE, KEY_AMOUNT, KEY_CATEGORY, KEY_MEMO, KEY_TAG},
null, null, null, null, KEY_DATE + " desc");
}
After adding the new column to the database, my fetchAll function looks like:
public Cursor fetchAll() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_DATE,
KEY_CHECKNUM, KEY_PAYEE, KEY_AMOUNT, KEY_CATEGORY, KEY_MEMO, KEY_TAG},
null, null, null, null, KEY_DATE + " desc");
}

Categories