How can I solve SQLSyntaxErrorException in hsqldb? - java

I try to use HSQLDB embedded in program.
However, when I create table and insert data in the database, error occurs.
Following is part of error message.
java.sql.SQLSyntaxErrorException: unexpected token: MAR required: )
at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.fetchResult(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.executeUpdate(Unknown Source)
It occurs when I insert some data in the database.
This is my CREATE statement.
stmt.execute("CREATE TABLE IF NOT EXISTS readability ( id INTEGER NOT NULL IDENTITY,"
+ "LOC INTEGER DEFAULT NULL, " + "numOfComments INTEGER DEFAULT NULL,"
+ "numOfBlankLines INTEGER DEFAULT NULL," + "numOfBitOperators INTEGER DEFAULT NULL,"
+ "readability double DEFAULT NULL," + "username varchar(255) DEFAULT NULL,"
+ "storedTime datetime DEFAULT NULL," + "methodname varchar(255) DEFAULT NULL,"
+ "classname varchar(255) DEFAULT NULL," + "patternrate double DEFAULT NULL,"
+ "maxNestedControl INTEGER DEFAULT NULL," + "programVolume double DEFAULT NULL,"
+ "entropy double DEFAULT NULL,"
+ "CONSTRAINT username FOREIGN KEY (username) REFERENCES user (username) ON DELETE NO ACTION ON UPDATE NO ACTION"
+ ");");
This is my INSERT statement.
stmt.executeUpdate(
"INSERT INTO readability (LOC, numOfComments, numOfBlankLines, numOfBitOperators,"
+ " readability, username, storedTime, methodname, classname, patternRate, maxNestedControl, programVolume, entropy) VALUES("
+ readability.getLOC() + ", " + readability.getNumOfComments() + ", "
+ readability.getNumOfBlankLines() + ", " + readability.getNumOfBitOperators() + ", "
+ readability.getReadability() + ", '" + readability.getUser().getUsername() + "', "
+ readability.getStoredTime() + ", '" + readability.getMethodName() + "', '"
+ readability.getClassName() + "', " + readability.getPatternRate() + ", "
+ readability.getMaxNestedControl() + ", " + readability.getProgramVolume() + ", "
+ readability.getEntropy() + ")",
Statement.RETURN_GENERATED_KEYS);
The object readability has all attributes used.

Do not concatenate values into a query string. Your code is vulnerable to SQL injection, and it is probably also the cause of the error. Use a prepared statement with parameter placeholders and set the values with the appropriate setters.
Your code would then become something like (leaving out a lot of columns for brevity):
try (PreparedStatement insert = connection.prepareStatement(
"insert into readability (LOC, username) values (?, ?)",
Statement.RETURN_GENERATED_KEYS)) {
insert.setInt(readability.getLOC();
insert.setString(readibility.getUser().getUsername());
insert.executeUpdate();
// handle generated keys...
}
You might also want to consider using an ORM like Hibernate.

Related

No database selected Error While Creating Table in MySQL with Java

I have Created a database with this code Some days ago
sql = "Create Database if not exists My_Test_Project";
stmnt.executeUpdate(sql);
And Created Some tables at that time. Now I'm creating two new tables in it one with this query
sql = "CREATE TABLE if not exists My_Test_Project.Sales_Invoice_Help "
+ "(inv_help_id INTEGER,"
+ "item VARCHAR(255),"
+ "qty INTEGER,"
+ "rate DECIMAL (7, 2),"
+ "total DECIMAL (7, 2),"
+ "sale_inv_id INTEGER,"
+ " PRIMARY KEY (inv_help_id),FOREIGN KEY (sale_inv_id) REFERENCES Sales_Invoice (sale_inv_id))";
stmnt.executeUpdate(sql);
And when I Executed my program it throw Exception
SEVERE: null
java.sql.SQLException: No database selected
But at the same time this query executed successfully
sql = "CREATE TABLE if not exists My_Test_Project.Sales_Invoice "
+ "(sale_inv_id INTEGER not NULL, "
+ "date VARCHAR(255), "
+ "acc_name VARCHAR(255),"
+ "due_date VARCHAR(255),"
+ "customer_name VARCHAR(255),"
+ "receipt_no VARCHAR(255),"
+ "freight_charges INTEGER,"
+ "deliver_to VARCHAR(255),"
+ "deliver_date VARCHAR(255),"
+ "total INTEGER,"
+ "discount INTEGER,"
+ "g_total INTEGER ,"
+ " PRIMARY KEY (sale_inv_id))";
stmnt.executeUpdate(sql);
Note: Sales_Invoice table is first in sequence and in code too.
I do not know why its throwing exception. Can you please guide me.
I would believe in this line you will need to add the Database name:
REFERENCES Sales_Invoice (sale_inv_id)
So it should now be:
REFERENCES My_Test_Project.Sales_Invoice (sale_inv_id)

Cant create table with preparedStatement

I can't create a table in the database (mySQL), using preparedStatement and try to enter name of future table with preparedStatement.setInteger():
static String queryCreateTable = "CREATE TABLE ?" +
"(ID INTEGER not NULL ," +
"BRAND VARCHAR(40)," +
"MODEL VARCHAR(40)," +
"YEAR INTEGER not NULL," +
"NOVELTY BINARY," +
"PRIMARY KEY ( ID ))";
And then I try to construct and call the statement after inputing name of table by user:
newNameOfTable = JOptionPane.showInputDialog("Connected for saving data. " +
"Input name of new table:");
pStatement = connection.prepareStatement(queryCreateTable);
pStatement.setString(1, newNameOfTable);
pStatement.executeUpdate();
It works well if I try to execute it without entering name (like a constant string: "CREATE TABLE newtable (...)" but I need to enter name..
You will have to format the string after reading the table name, something like:
static String queryCreateTable = "CREATE TABLE {0}" +
"(ID INTEGER not NULL ," +
"BRAND VARCHAR(40)," +
"MODEL VARCHAR(40)," +
"YEAR INTEGER not NULL," +
"NOVELTY BINARY," +
"PRIMARY KEY ( ID ))";
then create like:
newNameOfTable = JOptionPane.showInputDialog("Connected for saving data. " +
"Input name of new table:");
statement = connection.createStatement();
statement.execute(MessageFormat.format(queryCreateTable, newNameOfTable));
newNameOfTable = JOptionPane.showInputDialog("Connected for saving data. " +
"Input name of new table:");
static String queryCreateTable = "CREATE TABLE " + newNameOfTable +
"(ID INTEGER not NULL ," +
"BRAND VARCHAR(40)," +
"MODEL VARCHAR(40)," +
"YEAR INTEGER not NULL," +
"NOVELTY BINARY," +
"PRIMARY KEY ( ID ))";
pStatement = connection.prepareStatement(queryCreateTable);
pStatement.executeUpdate();
PreparedStatement example:
http://tutorials.jenkov.com/jdbc/preparedstatement.html

Creating Variable Table Name in SQL through Java?

I am trying to make a variable Table name through Java.
My code is :
public void createTable(String tableName){
try {
Statement stmt = con.createStatement();
stmt.executeUpdate("CREATE TABLE '"+tableName+"'" +
"(id INTEGER not NULL, " +
" username VARCHAR(255), " +
" pass VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))");
}
catch (SQLException e){
e.printStackTrace();
}
}
It gives me a syntax error saying:
Incorrect syntax near 'VariableTableNameIChose'.
Does anyone have any ideas?
It could be one of 2 things or the combination of both.
Maybe the single quotes around the table name are not valid in your database. So do like this:
stmt.executeUpdate("CREATE TABLE "+tableName+" " +
"(id INTEGER not NULL, " +
" username VARCHAR(255), " +
" pass VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))");
Or maybe you need a spaces between the table name and the ( following after:
Statement stmt = con.createStatement();
// v this one was missing
stmt.executeUpdate("CREATE TABLE '"+tableName+"' " +
"(id INTEGER not NULL, " +
" username VARCHAR(255), " +
" pass VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))");
The table name is an identifier. Identifiers do not use single quotes (in standard SQL).
"CREATE TABLE '"+tableName+"' "
Will result in
CREATE TABLE 'foobar'
which is invalid SQL. You need to remove the single quotes:
"CREATE TABLE "+tableName+" " + ...
As the table name is apparently a user input, you might actually want to use quoted identifiers (although this is in general a bad idea). Identifiers are quoted using double quotes in the SQL standard:
"CREATE TABLE \""+tableName+"\" " + ...

Unable to insert record in MySql using JAVA

I am new to Java and MYSql in fact using this combination first time and facing real trouble. I want to insert few records in a table but unable to do so. Following are the fields and datatype in the table named tbl_cdr in MySql.
**Field** **Type**
DATEANDTIME datetime NULL
VALUE1 int(50) NULL
VALUE2 varchar(50) NULL
VALUE3 varchar(50) NULL
VALUE4 varchar(50) NULL
VALUE5 varchar(50) NULL
The record I want to insert contains following values
2014-05-19 02:37:18, 405, MGW190514023718eab4, 923016313475, IN, ALERTSC
I am using following query and statements to Insert record in table
sqlQuery = "INSERT INTO tbl_cdr (DATEANDTIME,VALUE1,VALUE2,VALUE3,VALUE4,VALUE5)" + "VALUES ("+ forDateAndTime.format(date) + ", " + columnsList.get(1) + ", " + columnsList.get(2) + ", " + columnsList.get(3) + ", " + columnsList.get(4) + ", " + columnsList.get(5) + ")";
try
{
Statement qryStatement = conn.createStatement();
qryStatement.executeUpdate(sqlQuery);
qryStatement.close();
} catch (SQLException ex)
{
Logger.getLogger(CdrProject.class.getName()).log(Level.SEVERE, null, ex);
}
But when I reach the statement qryStatement.executeUpdate(sqlQuery); exception is thrown as:
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 '02:37:18, 405, MGW190514023718eab4,
923016313475, IN, ALERTSC)' at line 1
value2 ,value3 ,value4 and value 5 are varchars so it should be written within ''.
Do like this
sqlQuery = "INSERT INTO tbl_cdr (DATEANDTIME,VALUE1,VALUE2,VALUE3,VALUE4,VALUE5)" + "VALUES ("+ forDateAndTime.format(date) + ", " + columnsList.get(1) + ", '" + columnsList.get(2) + "',' " + columnsList.get(3) + "',' " + columnsList.get(4) + "',' " + columnsList.get(5) + "')";
You're inserting the date incorrectly. MySQL allows you to insert a string literal or a number.
You're trying to use 02:37:18 as a number, when really you should be using it as a string literal: '02:37:18'
Here is the MySql Reference describing this.
You're also not treating your varchars as strings either, they should be enclosed with quotes.

Java and Database Query?

Using Derby as my data base driver and tying to execute SQL query through java,
there was a error that was encounter, when tried to execute this particular query
stmt.executeQuery("insert into " + "TEST " + "values (" + dataTimeRev + ", "
+ dataType + "," + obj + ")" );
Here dataTimeRev, dataType and obj are variables with data.
The error that was stated was like this
java.sql.SQLSyntaxErrorException: VALUES clause must contain at least one element. Empty elements are not allowed.
if the column data type is VARCHAR you will have to pass the value in qoutes like 'value' for that you should do as below
String query = "insert into TEST values('"+dataTimeRev+"', '"+dataType+"','"+obj+"')";
stmt.executeQuery(query);
Verify that dataTimeRev, dataType and obj are not null and not blank.
I am not sure if Derby follows SQL syntax. But if the values are of type varchar, then it should be enclosed in single quotes ('). For example:
stmt.executeQuery("insert into " + "TEST " + "values ('" + dataTimeRev + " ', ' "
+ dataType + " ',' " + obj + " ')" );
Try this:
stmt.executeQuery("insert into TEST values ('" + dataTimeRev + "', "'+ dataType + "',"' + obj + "')" );
One of the causes of this error is trying to insert a Type that isn't a String (Date, Double, Integer e.t.c, surrounded by the single quotation mark ''
For example my table was declared like this:
String createTableStatement = "CREATE TABLE PRODUCT"+ "(product_id INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1)," +
"product_name CHAR(80), "+
"price DOUBLE," +
"supplier CHAR(50))";
So I was doing:
statement.executeUpdate("INSERT INTO PRODUCT (PRODUCT_NAME, PRICE, DATE_SUPPLIED, QUANTITY, SUPPLIER) VALUES " +
"('" + productName + "', " + "'" + price + "', " + "'" + supplier +"')");
instead of:
statement.executeUpdate("INSERT INTO PRODUCT (PRODUCT_NAME, PRICE, DATE_SUPPLIED, QUANTITY, SUPPLIER) VALUES " +
"('" + productName + "', " + price + ", " + "'" + supplier +"')");

Categories

Resources