mySQL syntax error when using an integer - java

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.

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

Creating function in MySQL version 5.7 through Java

This is my function:
query = "CREATE FUNCTION CheckSex(personID INT, G CHAR) " +
"RETURNS BIT " +
"BEGIN " +
"DECLARE Flag BIT; " +
"SET Flag = 1; " +
"If (G NOT IN (SELECT Sex FROM PERSONS WHERE ID = personID)) " +
"THEN SET Flag = 0; " +
"RETURN Flag; " +
"END";
pState = conn.prepareStatement(query);
pState.executeUpdate();
This is the error code:
check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
I have tried putting it into the mysql command line manually and I get an error after DECLARE Flag BIT;, also I have tried to change the delimiter which gave an error.
I have switched to an online compiler for now and this function works fine in MySql 2014 express written as follows
CREATE FUNCTION CheckSex(#personID AS INT, #G as CHAR)
RETURNS BIT
AS
BEGIN
DECLARE #Flag BIT = 1
If (#G NOT IN (SELECT Sex FROM PERSONS WHERE ID = #personID))
SET #Flag = 0
RETURN #FLAG
END;
Thank you for any feedback.

Pass email as a parameter for SQL query, PostreSQL, JAVA

I'm trying to pass the email as a parameter for the SELECT SQL query in my JAVA back-end.
As i understood, for some reason it pass only "email_name" from the "email_name#email.com". (Getting this error):
Threw a SQLException creating the list of blogs.
ERROR: column "email_name" does not exist
Position: 174
There is an existed rows, which contains "email_name#email.com".
(Why "ERROR: column"? according to query it should look for a value, no?)
Here is My query:
String active_user = "email_name#email.com"; //email_name#email.com - example, active_user receive some path variable and on this particular moment(before query execution) contains exactly "email_name#email.com".
ResultSet rs = st.executeQuery("SELECT \n" +
" goods.item_title, \n" +
" goods.item_descr, \n" +
" goods.item_email,\n" +
" goods.item_images,\n" +
" goods.item_phone, \n" +
" goods.item_price \n" +
"FROM \n" +
" public.goods\n" +
"WHERE goods.owner = "+active_user+"\n" +
"ORDER BY\n" +
" goods.item_id ASC;");
So the question is - how to pass full email to query?
Try using String active_user = "'email_name#email.com'";. with single quotes. Since postgre recognized as column when you use double quotes.
You should use PreparedStatement. this is a example
Very unsafe approach, you should use PreparedStatement to avoid SQL injection. Here is existing answer

Exception while input a date into a MySQL database

I have a MySQL database and want to write a row into it. The problem is that MySQL do not like my query, why? This is my code:
java.sql.Timestamp date = new java.sql.Timestamp(new java.util.Date().getTime());
for (Integer articlevalue : articlesendlist) {
for (Integer suppliervalue : suppliersendlist) {
connection.executeQuery("INSERT INTO Bestellungen(Bestellung_ID, Artikel_ID, Lieferant_ID, Datum, Preis) VALUES (" + maxorder + ", " + articlevalue + ", " + suppliervalue + ", " + date + ", NULL)");
}
}
A small description for my code. The articlesendlist contains IDs from selected values from a JTabel. The same applies to the suppliersendlist. I want to write the IDs into the table "Bestellung". The variable maxorder is the current ID for the table "Bestellung".
If you need it, the exception 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 '12:45:06.164, NULL)' at line 1
Please do not comment/answer with other links, I already searched for the problem and read several sites. They do not help me or are not suitable for my problem.
Thank you for help
Exception is obvious isn't it.
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 '12:45:06.164, NULL)' at line 1
You are not using quotes around date field.
However you should really avoid executing your SQL queries like this and use PreparedStatemens for this purpose.
PreparedStatemens has specific methods like setDate, setTime, setLong, setString etc and you don't need to worry about putting right quotes in your code.
Try changing this line:
connection.executeQuery("INSERT INTO Bestellungen(Bestellung_ID, Artikel_ID, Lieferant_ID, Datum, Preis) VALUES (" + maxorder + ", " + articlevalue + ", " + suppliervalue + ", " + date + ", NULL)");
to this:
connection.executeQuery("INSERT INTO Bestellungen(Bestellung_ID, Artikel_ID, Lieferant_ID, Datum, Preis) VALUES ('" + maxorder + "','" + articlevalue + "','" + suppliervalue + "','" + date + "','NULL')");

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