MySQLSyntaxErrorException when creating table - java

I am fairly new to MySQL with Java, but I have executed a few successful INSERT queries however cannot seem to get the CREATE TABLE query to execute without getting the MySQLSyntaxErrorException exception. My code is as follows:
Statement stmt;
String url = "jdbc:mysql://localhost:3306/mysql";
Connection con = DriverManager.getConnection(url, "root", "password");
stmt = con.createStatement();
String tblSQL = "CREATE TABLE IF NOT EXISTS \'dev\'.\'testTable\' (\n"
+ " \'id\' int(11) NOT NULL AUTO_INCREMENT,\n"
+ " \'date\' smallint(6) NOT NULL\n"
+ ") ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;";
stmt.executeUpdate(tblSQL);
stmt.close();
con.close();
And the error is as follows:
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 ''dev'.'testTable' (
'id' int(11) NOT NULL AUTO_INCREMENT,
'date' smallint(6) N' at line 1
I would appreciate it if anyone could spot the mistake in this query, as I've tried executing this within phpMyAdmin and it works as it should.

\n will make press enter effect :) make it like
String tblSQL = "CREATE TABLE IF NOT EXISTS `dev`.`testTable`"
+ "("
+ "id INTEGER(11) NOT NULL AUTO_INCREMENT primary key,"
+ "date smallint(6) NOT NULL"
+ ")"
+ "ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;";

Related

JDBC "Error in MySQL Syntax" when trying to switch to (USE) a database

I've been trying to use this code to create a table in a database that the code before this created successfully.
//Creates "Parts" Table if it's not already created.
public void createTableIfNecessary() throws SQLException{
String createString =
"USE inventory; " +
"CREATE TABLE IF NOT EXISTS parts " +
"(part_name TEXT NOT NULL, remaining_amt INT NOT NULL, " +
"restock_amt INT, barcode TEXT, location TEXT, part_id INT NOT NULL AUTO_INCREMENT);";
Statement createTable = this.con.createStatement();
createTable.execute(createString);
System.out.println("Table created or already existed: Parts");
}
My code to connect to the Database server:
try{Class.forName("com.mysql.jdbc.Driver");} catch(Exception e){
e.printStackTrace();
}
this.con = null;
Properties connectionProps = new Properties();
connectionProps.put("user", this.userName);
connectionProps.put("password", this.password);
this.con = DriverManager.getConnection("jdbc:mysql://" + this.serverName + ":" + this.portNumber + "/", connectionProps);
System.out.println("Connected to MySQL Database Server");
(This works, but it may be helpful to see)
My Error:
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 'CREATE TABLE IF NOT EXISTS parts (part_name TEXT NOT NULL, remaining_amt INT NOT' at line 1
I Assume it is just my incompetence with MySQL, but maybe someone here can see my syntax error. Thanks!
The USE inventory; statement is not appropriate in the context of a JDBC connection. You need to use Connection#setCatalog() to switch to a particular db. For more details, see
Java, how to change current database to another?
So do that and remove the USE clause from your SQL.
For auto_increment column in mysql, it has to be indexed. So you have to index part_id by making it a primary key or unique.
CREATE TABLE IF NOT EXISTS parts
(part_name TEXT NOT NULL,
remaining_amt INT NOT NULL,
restock_amt INT,
barcode TEXT,
location TEXT,
part_id INT NOT NULL AUTO_INCREMENT,
primary key (part_id));

JDBC Auto Increment

I am trying to create table that has column that auto increments the user id column. When I use the below code I get this error:
Exception in thread "main" java.sql.SQLSyntaxErrorException: ORA-00907: missing right parenthesis
String sql = "CREATE TABLE DBUSER("
+ "USER_ID NUMBER(5) NOT NULL AUTO_INCREMENT, "
+ "USERNAME VARCHAR(20) NOT NULL, "
+ "CREATED_BY VARCHAR(20) NOT NULL, "
+ "CREATED_DATE DATE NOT NULL, " + "PRIMARY KEY (USER_ID) "
+ ")"; Statement stmt;
stmt = connection.createStatement();
stmt.executeUpdate(sql);
It should work if you remove the auto-increment
CREATE TABLE DBUSER(
USER_ID NUMBER(5) NOT NULL,
USERNAME VARCHAR(20) NOT NULL,
CREATED_BY VARCHAR(20) NOT NULL,
CREATED_DATE DATE NOT NULL,
PRIMARY KEY (USER_ID)
)
Auto increment is not supported in Oracle

Mysql inserts the data as unknown values java

Hello i am using prepared statement to insert the values into mysql.
I am facing an issue in an string which is inserting as "c2a054656e6e6973c2a0" for value " Tennis " and i tried to use trim to trim the whitespace in front of the "Tennis" it did not work .From this question Why trim is not working? i tried using the solution poNumber.replace(String.valueOf((char) 160), " ").trim(); and it worked. can any one give solution for this?
SAMPLE CODE
CREATE TABLE `news1` (
`article_id` int(11) NOT NULL AUTO_INCREMENT,
`article_title` varchar(500) COLLATE utf8_bin NOT NULL,
`article_subcategory` varchar(255) COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`article_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=22 ;
//Sample category will be "Home » Tennis"
String category = item.getArticle_category();
String categoryArray[] = category.split("»");
preparedStatement = connect
.prepareStatement("INSERT INTO news1 VALUES(default,?,?)");
System.out.println(categoryArray[2].replace(String.valueOf((char) 160), " ")
.trim());
preparedStatement.setString(1, item.getArticle_title());
preparedStatement.setString(2, categoryArray[2]);
you are doing this categoryArray[2].replace(String.valueOf((char) 160), " ") .trim() in sys out but you do preparedStatement.setString(2, categoryArray[2]); in your statement
String temp = categoryArray[2].replace(String.valueOf((char) 160), " ") .trim();
System.out.println(temp);
and use temp in
preparedStatement.setString(2, temp);

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

Error with foreign key

I'm having problems with creating mySQL table within Java program. I constantly get Can't create table... errno: 150
Here is my code:
String URL="jdbc:mysql://192.168.1.128:3306";
Connection con=(Connection) DriverManager.getConnection(URL,user,pass);
Statement stmt=(Statement) con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
Statement stmt1=(Statement) con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String mySQL_new_table=("CREATE TABLE IF NOT EXISTS dbtest.T_AJPES_TR " + "(" + "row_count INT PRIMARY KEY AUTO_INCREMENT,"
+ "rn CHAR(15),sSpre CHAR(5),reg CHAR(5),eno VARCHAR(10),davcna VARCHAR(15),Ime VARCHAR(75),Priimek VARCHAR(75),LOG_ID INT,INDEX L_ID (LOG_ID),FOREIGN KEY(LOG_ID) references T_AJPES_TR_LOG(ID_LOG) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE = INNODB;");
String mySQL_log = ("CREATE TABLE IF NOT EXISTS dbtest.T_AJPES_TR_LOG" + "(ID_LOG INT PRIMARY KEY AUTO_INCREMENT, Date_import VARCHAR(45),File_import VARCHAR(75)) ENGINE = INNODB;");
stmt.executeUpdate(mySQL_new_table);
stmt1.executeUpdate(mySQL_log);
ResultSet uprs=stmt.executeQuery("SELECT * FROM dbtest.T_AJPES_TR");
ResultSet uprs1=stmt1.executeQuery("SELECT * FROM dbtest.T_AJPES_TR_LOG");
I googled many tutorials for creating foreign key and I still have problems. So what I'm doing wrong?
You've likely got an issue with foreign key constraints, see http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html for more details.
First one to check is whether your LOG_ID reference to T_AJPES_TR_LOG(ID_LOG) is correct

Categories