How to auto increment database column in Java derby? - java

Here's the SQL I've tried so far to create the table
CREATE TABLE tblPosts (nId INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
strContent VARCHAR(140) NOT NULL,
strLink VARCHAR(200),
strImage VARCHAR(200));
using
String sql = "INSERT INTO tblPosts VALUES ('" + textFieldContent.getText() + "', '" +
textFieldLink.getText() + "', '" + textFieldImage.getText() + "')";
I get an error telling me I'm not providing the nId column value which I'm not but if the column auto-increments I'm not supposed to right?
I've also tried using the IDE to create the table on the database as described here
Alter a table column with auto increment by 1 in derby
Same response though. Any suggestions?

You need to include Start with 1, Increment by 1
Like this
CREATE TABLE tblPosts (nId INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY(Start with 1, Increment by 1),
strContent VARCHAR(140) NOT NULL,
strLink VARCHAR(200)

I would guess that since you're not specifying the column names in the SELECT, it is getting confused as to which columns the data should go in. I would specify the column names in your INSERT command.

You need to set THAT auto_increment column to DEFAULT like this:
String sql = "INSERT INTO tblPosts VALUES ( DEFAULT, '" + textFieldContent.getText() + "', '" +
textFieldLink.getText() + "', '" + textFieldImage.getText() + "')";

Related

What is the correct code to make the user put the column names inside the table in Databases via SQL?

I used this code to have the user put the column name in the database / text =
"create table oop('"+id+"' varchar(30) not null,'"+name+"' varchar(20) not null,'"+lastname+"' varchar(20) notnull,'"+salary+"' varchar(30) not null) " ;
is error
What is the correct code to make the user put the column names inside the table in Databases via SQL?
Just remove the single quotes around the column name: they stand for literal strings, not for identifiers:
"create table oop(" + id + " varchar(30) not null," + name + " varchar(20) not null," + lastname + " varchar(20) notnull, " + salary + " varchar(30) not null)" ;
On the other hand, if your identifiers contain special characters, then you need to quote them: for this, use the relevant quoting character for your database: MySQL wants backticks, SQL Server has square brackets, ([]), Postgres and Oracle use the double quote "".
Make a PROCEDURE like:
CREATE PROCEDURE sproc_BuildTable
#TableName NVARCHAR(128)
,#Column1Name NVARCHAR(32)
,#Column1DataType NVARCHAR(32)
,#Column1Nullable NVARCHAR(32)
AS
DECLARE #SQLString NVARCHAR(MAX)
SET #SQString = 'CREATE TABLE '+#TableName + '( '+#Column1Name+' '+#Column1DataType +' '+#Column1Nullable +') ON PRIMARY '
EXEC (#SQLString)
GO
This stored procedure can be executed like this:
sproc_BuildTable 'Customers','CustomerName','VARCHAR(32)','NOT NULL'

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.

SQL replace into only the first two columns in a row

What I currently have is this:
PreparedStatement ps = getSQLConnection().prepareStatement(
"REPLACE INTO " + table + " (uuid,name) VALUES(?,?)"
);
ps.setString(1, uuid.toString());
ps.setString(2, name.toLowerCase());
ps.executeUpdate();
However it is not setting only index 1 and 2, but instead clears the other column values. How can I insert into a row with only the first 2 indexes, and leave the other values untouched?
The table is created with this statement:
"CREATE TABLE IF NOT EXISTS data (" +
"`uuid` varchar(36) NOT NULL," +
"`name` varchar," +
"`owner` varchar," +
"`tags` varchar," +
"PRIMARY KEY (`uuid`));"
From the documentation:
REPLACE is a MySQL extension to the SQL standard. It either inserts, or deletes and inserts. For another MySQL extension to standard SQL—that either inserts or updates—see Section 13.2.5.3, “INSERT ... ON DUPLICATE KEY UPDATE Syntax”.

creating a new mysql table using JAVA

I'm trying to create a table similar to a ready table I created before (a template, if you will) where the only variable should be the table name.
This is what I've tried so far:
I exported the template table to mysql code and copied the code to a preparedStatement object as such:
createNewLineTableStatement = constantLink.prepareStatement("CREATE TABLE IF NOT EXISTS ? (" +
" `index` int(5) NOT NULL," +
" `station` int(5) NOT NULL," +
" PRIMARY KEY (`index`)," +
" UNIQUE KEY `station` (`station`)" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;\");");
Than I try to execute the code by calling the following function:
private static boolean createNewLineTable(String tableName) throws SQLException{
createNewLineTableStatement.setString(1, tableName);
if (createNewLineTableStatement.executeUpdate() == Statement.EXECUTE_FAILED)
return false;
return true;
}
But I'm getting a syntax error exception:
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 ''line_37_var_1' ( `index` int(5) NOT NULL, `station` int(5) NOT NULL, PRIMARY' at line 1
How can I fix the code? OR is there a cleaner, better way to do the same thing? Maybe creating a script with a user variable? I thought of that but I've never used .sql script before.
Problem 1: You can't use a prepared statement parameter as the table name.
Problem 2: You have an unmatched paren and extra characters ");at the end of your statement.
Your query string should look something like:
String query = "CREATE TABLE IF NOT EXISTS `" + tableName + "` (" +
" `index` int(5) NOT NULL," +
" `station` int(5) NOT NULL," +
" PRIMARY KEY (`index`)," +
" UNIQUE KEY `station` (`station`)" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
by design, TableName and ColumnNames cannot be parameterized.
If you are scared about SQL Injection, create a custom function to check for malicious tableName. It is safe if the value comes inside of your application.
Then concatenate it in the string, add backtick for first level of defense :D
String tableName = "Your tableName";
String query = "CREATE TABLE IF NOT EXISTS `" + tableName + "` (" +
" `index` int(5) NOT NULL," +
" `station` int(5) NOT NULL," +
" PRIMARY KEY (`index`)," +
" UNIQUE KEY `station` (`station`)" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
You are missing Table name and i think that "?" shouldn't be there.
I will be something like
"CREATE TABLE IF NOT EXISTS YOURTABLE" + the following code

how can i redesign this query?

How can i redesign the following query to avoid errors :
String sqlQueryToMakeTable = "create table " + UserEmail +
"(" +
"NameOfThePhoto varchar(255)," +
"Caption varchar(255)" +
")";
// UserEmail is of type String
UserEmail is of the form user#host.com and when i execute the query i get these errors :
java.sql.SQLSyntaxErrorException: Lexical error at line 1, column 18. Encountered: "#" (64), after : "".
at org.apache.derby.client.am.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
at org.apache.derby.client.am.Connection.prepareStatement(Unknown Source)
at com.sun.gjc.spi.base.ConnectionHolder.prepareStatement(ConnectionHolder.java:562)
at com.sun.gjc.spi.jdbc40.ConnectionWrapper40.prepareCachedStatement(ConnectionWrapper40.java:255)
at com.sun.gjc.spi.jdbc40.ConnectionWrapper40.prepareCachedStatement(ConnectionWrapper40.java:52)
at com.sun.gjc.spi.ManagedConnection.prepareCachedStatement(ManagedConnection.java:964)
.....
I understand the reason for exception. I run this query directly by placing the email address in the double quotes but what do i do here ?
EDIT Can't we have # in table name ?
Most databases permit arbitrary characters in table names as long as you enclose them in the correct quotes for the DB. For example,
For MySQL:
"create table `" + UserEmail + "` " +
For DB2:
"create table \"" + UserEmail + "\" " +
For SQL Server:
"create table [" + UserEmail + "] " +
For Derby it looks like double quotes might work, like with DB2: http://db.apache.org/derby/docs/10.0/manuals/reference/sqlj08.html
Then again, why are you creating a table for each user??
Update: The usual approach is having a single table of captions that also contains some data that can be used to identify the user. For example:
CREATE TABLE PhotoCaptions (
UserEmail varchar(255),
NameOfThePhoto varchar(255),
Caption varchar(255)
)
Then, to find the caption for a particular photo of a particular user, you would use a query like this:
SELECT Caption FROM PhotoCaptions
WHERE UserEmail = 'email' AND NameOfThePhoto = 'photoname'
You are trying to make a table name liek an email address but you can't have a # in your table name. Replace it.
But as arnaud stated: Are you sure you want to create a table for every user?
Beter make a general email table with a column containing the userid.
EDIT:
You can have a # in your table name if you use backticks. Example:
create table `user#host.com` (id int);
But you shouldn't do that.
It depends on what database you are using. In sql server you need to use [table_name] in mysql you need 'table_name'
This will suppress any special character meaning in the table name
I think what you should do is to quote the UserEmail variable like this:
String sqlQueryToMakeTable = "create table \'" + UserEmail + "\'" +
"(" +
"NameOfThePhoto varchar(255)," +
"Caption varchar(255)" +
")";
i think this will work. Table names in mysql can have both . and # sign.

Categories