`I am having a problem with doing a PreparedStatement for Java ODBC MySQL. It seems to be cutting off the query, and giving a syntax error. I am not sure how to proceed, as I am only learning Java SQL at this point. I can't really do a self contained example because the problem involves databases, and it would get quite big.
The code with the problem is this..
public void insertEntry(
Hashtable<String, String> strings,
Hashtable<String, Integer> integers,
Date created, Date paid, boolean enabled)
throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
String dburl = "jdbc:mysql://" + dbHost + "/" + dbName +
"?user=" + dbUser + "&password=" + dbPass;
connect = DriverManager.getConnection(dburl);
ps = connect.prepareStatement("INSERT INTO " + dbName + ".users INSERT " +
"enabled=?, username=?, created=?, paid=?, alias=?, password=?, " +
"email=?, bitmessage=?, torchat=?, reputation=?," +
"privacy=?, fpmport=?, fpm-template=? ;");
java.sql.Date SQLcreated = new java.sql.Date(created.getTime());
java.sql.Date SQLpaid = new java.sql.Date(paid.getTime());
System.out.println("Debug: SQLpaid = " + SQLpaid.toString());
ps.setBoolean(1, enabled);
ps.setString(2, strings.get("username"));
ps.setDate(3, SQLcreated);
ps.setDate(4, SQLpaid);
ps.setString(5, strings.get("alias"));
ps.setString(6, strings.get("password"));
ps.setString(7, strings.get("email"));
ps.setString(8, strings.get("bitmessage"));
ps.setString(9, strings.get("torchat"));
ps.setInt(10, integers.get("reputation"));
ps.setInt(11, integers.get("privacy"));
ps.setInt(12, integers.get("fpmport"));
ps.setString(13, strings.get("fpm-template"));
ps.executeUpdate();
ps.close();
connect.close();
resultSet.close();
}
I get the following output when trying to use this method...
Debug: SQLpaid = 1990-03-21
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorEx ception: 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 'INSERT enabled=0, username='default_username', created='2000-03-21', paid='1990-' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInsta nce0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInsta nce(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newI nstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Construc tor.java:532)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:41 1)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLErro r.java:1054)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.ja va:4237)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.ja va:4169)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:26 17)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java :2778)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionIm pl.java:2834)
at com.mysql.jdbc.PreparedStatement.executeInternal(P reparedStatement.java:2156)
at com.mysql.jdbc.PreparedStatement.executeUpdate(Pre paredStatement.java:2441)
at com.mysql.jdbc.PreparedStatement.executeUpdate(Pre paredStatement.java:2366)
at com.mysql.jdbc.PreparedStatement.executeUpdate(Pre paredStatement.java:2350)
at database.Users.insertEntry(Users.java:297)
at test.dbUsers.main(dbUsers.java:95)
i think your doing some mistake in your code:
these are following as:
1. your mention INSERT and you should must change like SET
2. your adding the ;in your SQL Query you should remove that.
your code:
ps = connect.prepareStatement
("INSERT INTO " + dbName + ".users INSERT " #look here error to change 'set' +
"enabled=?, username=?, created=?, paid=?, alias=?, password=?, " +
"email=?, bitmessage=?, torchat=?, reputation=?," +
"privacy=?, fpmport=?, fpm-template=? ; " #remove this semicolon(;));
you should must change like as:
ps = connect.prepareStatement
("INSERT INTO " + dbName + ".users SET " +
"enabled=?, username=?, created=?, paid=?, alias=?, password=?, " +
"email=?, bitmessage=?, torchat=?, reputation=?," +
"privacy=?, fpmport=?, fpm-template=? ");
Change:
INSERT INTO " + dbName + ".users INSERT "
To:
INSERT INTO " + dbName + ".users SET "
Refer to:
MySQL: INSERT Syntax
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name
[PARTITION (partition_name,...)]
SET col_name={expr | DEFAULT}, ...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ... ]
Related
Well, I have got some problems with this sql syntax.
public static void newTable(String tableName, String columnName, String columnType) {
try {
PreparedStatement pst = conn.prepareStatement
("CREATE TABLE `" + tableName + "`" + "(`" +columnName + "` `" + columnType + "` )");
//PreparedStatement pst = conn.prepareStatement("CREATE TABLE teszt2 ( asd VARCHAR(255) );" ); //THIS IS WORKING
//pst.setString(1, tableName);
//pst.setString(2, columnName);
//pst.setString(3, columnType);
pst.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
This is the error that I got:
Every time I run this I got this error. I assume that I have some problems with my query.
Although, the one without strings in it is working fine.
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 '`VARCHAR(255)` )' at line 1
According to the comments in your code, this works:
CREATE TABLE teszt2 ( asd VARCHAR(255) );
But this doesn't:
CREATE TABLE `teszt2` ( `asd` `VARCHAR(255)` );
So I guess remove the back-ticks and use the "working" version:
PreparedStatement pst = conn.prepareStatement
("CREATE TABLE " + tableName + " (" +columnName + " " + columnType + " )");
Or at least remove them from the type specifier:
PreparedStatement pst = conn.prepareStatement
("CREATE TABLE `" + tableName + "`" + "(`" +columnName + "` " + columnType + " )");
I've got the following code in my app
String sql = "SELECT colA, colB, colC " +
"FROM " + tblName + " WHERE UserId = " + userId +
" AND InsertTimestamp BETWEEN " + lastDate +
" AND " + DataProcessor.TODAY + " ORDER BY UserId, Occurred";
try{
if(null == conn)
openDatabaseConnection();
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery(); <------- this is the line which throws the SQL exception
retArray = this.getArrayListFromResultSet(rs);
}catch(SQLException sqle){
JSONObject parms = new JSONObject();
eh.processSQLException(methodName, sqle, sql, parms);
}
So when I run my app in the debugger, I get this exception message
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 '00:00:00.0 AND 2014-08-20 00:00:00.0 ORDER BY UserId, Occurred' at line 1
I'm reasonably certain that there's simple and reasonable solution to this, but I have not been able to find it.
I've tried looking in the MySQL manual for a solution or a different format.
I've tried running my timestamps through a TIMESTAMP() functino and a DATE() function in the SQL, neither of which helped.
I pulled the fully formed SQL out of the Java code and ran it in MySQL Workbench with no issues, what-so-ever. So now I'm looking to the experts for help.
Dates in SQL must be enclosed within single quotes like strings.
As you're using a prepared statemtent, why you don't use '?' and stmt.setDate(...)?
String sql = "SELECT colA, colB, colC " +
"FROM " + tblName + " WHERE UserId = ?" +
" AND InsertTimestamp BETWEEN ?" +
" AND ? ORDER BY UserId, Occurred";
try {
if(null == conn) {
openDatabaseConnection();
}
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, userId);
stmt.setDate(2, lastDate);
stmt.setDate(3, DataProcessor.TODAY);
ResultSet rs = stmt.executeQuery();
retArray = this.getArrayListFromResultSet(rs);
} catch(SQLException sqle) {
JSONObject parms = new JSONObject();
eh.processSQLException(methodName, sqle, sql, parms);
}
Anyway, I think you are setting the dates in the opposite order. You should put first 'today' then lastDate. Although I don't know your constraints...
I have seen lot of answers over here regarding my question, but can not find solution for it. I am reading a excel file and storing in mysql database. This is my code
PreparedStatement sql_statement = (PreparedStatement) con
.prepareStatement("insert into medtest(FMCODE,FLAG,MCODE,EMPNO,NAME,ADDRESS1,ADDRESS2,ADDRESS3,BALANCE,HOSPITAL_O,HOSPITAL_I,NURSING,GENERAL,PRIVATE,SPLCODE,BKCD,ACCOUNT_NO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
wb = WorkbookFactory.create(new File(filePath));
// System.out.println(wb.getSheetName());
Sheet mySheet = wb.getSheetAt(0);
for (Row row : mySheet) {
String fmcode = row.getCell(0).getStringCellValue();
String flag = row.getCell(1).getStringCellValue();
int mcode = (int) row.getCell(2).getNumericCellValue();
String empno = row.getCell(3).getStringCellValue();
String name = row.getCell(4).getStringCellValue();
String address1 = row.getCell(5).getStringCellValue();
String address2 = row.getCell(6).getStringCellValue();
String address3 = row.getCell(7).getStringCellValue();
double balance = (double) row.getCell(8).getNumericCellValue();
double hospital_o = (double) row.getCell(9)
.getNumericCellValue();
double hospital_i = (double) row.getCell(10)
.getNumericCellValue();
double nursing = (double) row.getCell(11).getNumericCellValue();
double general = (double) row.getCell(12).getNumericCellValue();
double prvte = (double) row.getCell(13).getNumericCellValue();
String splcode = row.getCell(14).getStringCellValue();
String bkcd = row.getCell(15).getStringCellValue();
String account_no = row.getCell(16).getStringCellValue();
String sql = "insert into medtest values('" + fmcode + "','"
+ flag + "','" + mcode + "','" + empno + "','" + name
+ "','" + address1 + "','" + address2 + "','"
+ address3 + "','" + balance + "','" + hospital_o
+ "','" + hospital_i + "','" + nursing + "','"
+ general + "','" + prvte + "','" + splcode + "','"
+ bkcd + "','" + account_no + "')";
PreparedStatement ps = (PreparedStatement) con
.prepareStatement(sql);
ps.executeUpdate();
When i am inserting my excel file into database getting the below exception, how to solve it.
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
'S DENTAL CLINIC','KINGSWAY CAMP, DELHI.','0.0','0.0','0.0','0.0','0.0','0.0','nu'
at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
...
The error is pointing to the ps.executeUpdate(); line.
Replace
sql_statement.executeUpdate() with ps.executeUpdate().
You are trying to execute preparedstatement sql_statement without setting the parameters. Either you can set the parameters and invoke sql_statement.executeUpdate() or simply replace sql_statement.executeUpdate with ps.executeUpdate().
The error message tells you exactly what's wrong - your query is broken around 'S DENTAL CLINIC'. My guess is this is part of a larger string, like BOB'S DENTAL CLINIC - do you see the problem now? The string you're trying to insert into the query contains a ', breaking the rest of the query.
The right thing to do here, as already suggested, is to use Prepared Statements. You should never construct dynamic SQL statements via string concatenation; not only does it risk these sort of syntax errors, but it's also the cause of SQL injection attacks.
Some related questions:
How to use prepared statement
When should we use a PreparedStatement instead of a Statement?
How can prepared statements protect from SQL injection attacks?
I have a customer that needs a large number of updates done in the database. I have finished trying to persuade them this can be done more cleanly. They want to run a select statement with a "for update nowait" on a select row and then you they want to run the update statement. I have tried this a number of ways but I am getting errors.
String selectQuery = " Select * from " + table + " where column=\'" + column + "\' FOR UPDATE NOWAIT";
String updateQuery = " UPDATE " + table + " SET newcolumn = \'" + newValue + "\' WHERE column = \'" + column + "\' ";
Connection connection = null;
try
{
connection = DriverManager.getConnection(dbURL, dbUsername, dbPassword);
Statement stmt = connection.createStatement();
stmt.addBatch(selectQuery);
stmt.addBatch(updateQuery);
stmt.addBatch(commit);
int [] updateCounts = stmt.executeBatch();
stmt.close();
}
This gets exception:
invalid batch command: invalid SELECT batch command 0
26736 [Thread-11_DataConversion] ERRORDTL - [1424462365738]java.sql.BatchUpdateException: invalid batch command: invalid SELECT batch command 0
at oracle.jdbc.driver.OracleStatement.executeBatch(OracleStatement.java:4462)
at oracle.jdbc.driver.OracleStatementWrapper.executeBatch(OracleStatementWrapper.java:213)
at .BatchTokenizationAgent.executeJob(BatchTokenizationAgent.java:246)
at com.yantra.ycp.agent.server.YCPAbstractAgent.executeOneJob(YCPAbstractAgent.java:392)
at com.yantra.ycp.agent.server.YCPAbstractAgent.processMessage(YCPAbstractAgent.java:294)
at com.yantra.ycp.agent.server.YCPAbstractAgent.run(YCPAbstractAgent.java:160)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
I have also tried:
String selectQuery = " Select * from " + table + " where column=\'" + column + "\' FOR UPDATE NOWAIT; UPDATE " + table + " SET newcolumn = \'" + newValue + "\' WHERE column = \'" + column + "\' ";
Connection connection = null;
try
{
connection = DriverManager.getConnection(dbURL, dbUsername, dbPassword);
Statement stmt = connection.createStatement();
stmt.execute(selectQuery);
stmt.execute(updateQuery);
stmt.close();
}
This gets exception:
java.sql.SQLSyntaxErrorException: ORA-00911: invalid character
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:439)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:395)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:802)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:436)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:186)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:521)
at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:194)
at oracle.jdbc.driver.T4CStatement.executeForDescribe(T4CStatement.java:853)
at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1145)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1267)
Can someone please point in the correct direction? Thank you so much. This is to be one time job and just needs to work with minimum work needed.
I need to use an INSERT statement, and 2 of the records in this statement are fields which are calculated in the program, and need to be added to the database.
System.out.println("Executing....");
stmt = conn.createStatement();
String sql;
sql = "INSERT INTO Identities"
+ " VALUES"
+ "('John', 'Smith', '38 Turpington Lane', 'Farnborough', 'Hampshire', 'HA6 7AF', '1990-03-01', PKmod, PKexpo)";
stmt.executeUpdate(sql);
'PKmod' and 'PKexpo' are BigInteger fields whose value is calculated in the java program, how can I add these values to the database?
Thanks for any help! :)
Please do not insert sqls this way. Use prepared statement. Change your sql to use "?" markers instead of concatenating values.
It depends on the DBMS. For mysql perhaps BIGINT should suffice?
http://dev.mysql.com/doc/refman/5.0/en/numeric-type-overview.html
You need to concatenate the string!!!!
So do as follows:
sql = "INSERT INTO Identities"
+ " VALUES"
+ "('John', 'Smith', '38 Turpington Lane', 'Farnborough', 'Hampshire', 'HA6 7AF', '1990-03-01',"+ PKmod+", "+PKexpo+")";
System.out.println("Executing....");
stmt = conn.createStatement();
String sql;
sql = "INSERT INTO Identities"
+ " VALUES"
+ "('John', 'Smith', '38 Turpington Lane', 'Farnborough', 'Hampshire', 'HA6 7AF', '1990-03-01', "
+ PKmod
+ ", "
+ PKexpo
+ ")";
stmt.executeUpdate(sql);
// First Check That PKmod & PKexpo values are not Zero Or Null.
System.out.println("Executing....");
String sql = "INSERT INTO Identities"
+ " VALUES"
+ "('John', 'Smith', '38 Turpington Lane', 'Farnborough', 'Hampshire', 'HA6 7AF', '1990-03-01'," + PKmod + "," + PKexpo +")";
PreparedStatement pStmt = null;
pStmt = con.prepareStatement(sql);
pStmt.executeUpdate();
closePreparedStatement(pStmt);