how can i redesign this query? - java

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.

Related

I'm trying to create a customize id or unique id like SID0000001, but there's an error: '(' , ')', <column constraint> or comma expected, got'+'

So this is were the error occur on CON_SID + "AS 'SID' + RIGHT('000000' + CAST(ID AS VARCHAR(6)),6)PERSISTED);";
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TBL_Name +
" ("+ CON_ID + "INT IDENTITY(1,1) NOT NULL PRIMARY KEY AUTOINCREMENT, "+
CON_Name + " TEXT, " +
CON_Address + " TEXT, " +
CON_BDay + " TEXT, " +
CON_Gender + " TEXT, " +
CON_Course + " TEXT, " +
CON_SID + "AS 'SID' + RIGHT('000000' + CAST(ID AS VARCHAR(6)),6)PERSISTED);";
db.execSQL(query);
}
You cannot use MYSQL's dialect of SQL. However, you could mimic the result by utilising a TRIGGER (not that you need to - explained below) for example :-
First create the table (names based upon your question) e.g. :-
CREATE TABLE IF NOT EXISTS example (
id INTEGER PRIMARY KEY,
name TEXT,
address TEXT,
bday TEXT,
gender TEXT,
course TEXT,
sid TEXT UNIQUE
);
note AUTOINCREMENT dropped, see link
Then add the TRIGGER using :-
CREATE TRIGGER IF NOT EXISTS example_after_insert AFTER INSERT ON example
BEGIN
UPDATE example SET sid = 'SID'||substr('000000',1,6-length(id))||id WHERE id = new.id;
END
;
The SID would then be generated whenever a row is inserted. For example :-
/* INSERT rows where id column is generated by SQLite */
INSERT INTO example (name,address,bday,gender,course) VALUES
('name1','addr1','bday1','female','course1'),
('name2','addr2','bday2','male','course2'),
('name3','addr3','bday3','female','course3')
;
/* INSERT rows with specific ID's to test values */
INSERT INTO example (id,name,address,bday,gender,course) VALUES
(15,'name1','addr1','bday1','female','course1'),
(135,'name2','addr2','bday2','male','course2'),
(1234,'name3','addr3','bday3','female','course3'),
(98765,'name3','addr3','bday3','female','course3'),
(999999,'name3','addr3','bday3','female','course3'),
(9999999,'name3','addr3','bday3','female','course3') /* overflow */
;
Using SELECT * FROM example; then shows :-
Not that you need to
You could achieve the same result without the trigger by simply generating the column when needed.
This approach would afford the following benefits
reduce the storage space required
reduce the processing required when inserting a row
no extra column
no trigger and update
no additional index conflict checking
conform better with normalisation (not duplicating data)
For example to get the same result without accessing the sid column (i.e. showing that it's not needed) you could use (the generated column has been named schoolID ):-
SELECT
id,
name,
address,
bday,
gender,
course,
'SID'||substr('000000',1,6-length(id))||id AS schoolID
FROM example;
The result :-

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'

How to auto increment database column in Java derby?

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() + "')";

mySQL syntax error when using an integer

I'm trying to create a table using mySQL and Java. What I have is:
String sql = "CREATE TABLE IF NOT EXISTS " + Userinput.getTableName2() +
" (participant INT(255), " +
" 0 INT(255),"+
" name INT(3), " +
" occurances INT(255))";
stmt.executeUpdate(sql);
The Zero naming the second column is arbitrary, but I will need to have the column name be an integer.
The error I'm getting is:
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 '0 INT(255), name INT(3), occurances INT(255))' at line 1
I would appreciate any and all help! Thanks!
According to this http://dev.mysql.com/doc/refman/5.0/en/identifiers.html
Identifiers may begin with a digit but unless quoted may not consist
solely of digits.
so you have to quote the 0
String sql = "CREATE TABLE IF NOT EXISTS " + Userinput.getTableName2() +
" (participant INT(255), " +
" `0` INT(255),"+ // using backticks
" name INT(3), " +
" occurances INT(255))";
stmt.executeUpdate(sql);
Although, it seems a dumb name for a column.
Please read mysql documentation:
http://dev.mysql.com/doc/refman/5.1/en/identifiers.html
Identifiers may begin with a digit but unless quoted may not consist
solely of digits.

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

Categories