How to create table name acording to input value? - java

i want to make table according how user select value.if user select some value ...this value is used as table name in servlet.
I tried this ...is it valid?
String tbl = Branch + Year + Month;
st.executeUpdate("CREATE TABLE" + tbl + "(Month varchar(10),purva varchar(10),yash varchar(10)");

Setting aside the potential of SQL injection attacks, you're missing spaces around the name of the table:
st.executeUpdate("CREATE TABLE " + tbl + " (Month varchar(10), purva varchar(10), yash varchar(10)");
// Here ----------------------^-----------^

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 :-

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

SQLite delete a specific row java swing

I'm trying to delete a specific row from a table, and I can't find the way to do it.
I was following https://groups.google.com/forum/#!topic/android-developers/rrmbsKyKRCE but it didn't work.
my query is:
String query = "delete from " + type + " where name=? and score =? (SELECT score FROM " + type + " ORDER BY score DESC LIMIT 1)";
pst.setString(1, tempName);
pst.setInt(2, tempScore);
The string "type" is the table name (no bugs with the table name) and in the table I have to rows: name and score. and pst is the prepared statement.
The error I get: "[SQLITE_ERROR] SQL error or missing database (near "(": syntax error)".
I've noticed that the link above is for android, but I couldn't find something for java swing...
What am I doing wrong?
It seems you're looking for an IN clause
String query = "delete from " + type + " where name=? and score IN (SELECT score FROM " + type + " ORDER BY score DESC LIMIT 1)";

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”.

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