inserting column headings into hsqldb text file - java

I'm modifying someone else's Java code, learning Java as I go. :-). I'm writing hsqldb TEXT files, and I would like the final files to have a 'heading' row, so that they can be more easily understood as plain text. hsqldb has a switch 'ignore_first=true' for reading such files, but I can't find a way to write the line in. It may not exist, but there is a tantalizing reference to SOURCE HEADER in the documentation. Does anyone know how to use it?
Here is a simplified sample of what I have tried:
String createtextTable =
"CREATE TEXT TABLE MolSet (" +
" id INT NOT NULL IDENTITY," +
" filename VARCHAR(300)," +
" expSolFilename VARCHAR(300)," +
" variance DOUBLE" + ");" ;
String headingsTable = "id,filename,expSolFilename, variance";
try
{
stmt = conn.createStatement();
stmt.execute(createtextTable);
setTableStmt = "SET TABLE " + “MolSet” + " SOURCE " +
'"' + TABLES[0] + ".csv;ignore_first=true" + '"';
stmt.execute(setTableStmt);
headingStmt = "SET TABLE " + “MolSet” + " SOURCE HEADER " +
'"' + headingsTable + '"';
stmt.execute(headingStmt);
}
catch( SQLException sqle )
{
return false;
}
return true;
}
this gives sql error:
Invalid TEXT table source string in statement [SET TABLE MolSet SOURCE HEADER]
I hope you can help, even if it is to confirm it is impossible. Thanks,
Jocelyn

The source and source header strings must be enclosed in single quotes:
SET TABLE MolSet SOURCE HEADER 'id,filename,expSolFilename,variance'
You have used double quotes instead.
Edit: The answer is for the latest version. Older versions since 1.8.x support this, but may require double quotes. The number of columns in the header and table must match. Alternatively, you can edit the text source while the database is offline and add the headers yourself.

This SQL file works for making CSV text files from a table and also sets field headers. It is specific for HSQLDB (version 1.8.1.3).
Website for database DL and docs is HSQLDB.ORG
I hope it helps.
-- ========================
-- MAKE TABLE TEXT_TABLE_01
-- ========================
DROP TABLE TEXT_TABLE_01 IF EXISTS;
CREATE TEXT TABLE TEXT_TABLE_01
( ID_NUMBER INTEGER
, FIRST_NAME VARCHAR(30)
, LAST_NAME VARCHAR(30)
, DEAR_ VARCHAR(50)
)
;
SET TABLE TEXT_TABLE_01 SOURCE "TEXT_TABLE_01.TXT;ignore_first=true;fs=:";
SET TABLE TEXT_TABLE_01 SOURCE HEADER "ID_NUMBER:FIRST_NAME:LAST_NAME:DEAR_";
INSERT INTO TEXT_TABLE_01
( ID_NUMBER, FIRST_NAME, LAST_NAME, DEAR_ )
SELECT
ID_NUMBER, FIRST_NAME, SURNAME, DEAR_
FROM
TMP_NON_PERSONAL
;
SELECT * FROM TEXT_TABLE_01;
SET TABLE TEXT_TABLE_01 SOURCE OFF;
-- DELETE ALL TEXT FILES WHEN FINISHED ... OR BEFORE STARTING ...

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 create table name acording to input value?

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

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.

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