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 + " )");
Related
I'm trying to creat a table in sqlight. I use the following code
// this will now through a exception becouse the table allready exist
sql = "CREATE TABLE IF NOT EXISTS exchangesd (\n"
+ " id integer PRIMARY KEY,\n"
+ " name text ,\n"
+ " publickey ,\n"
+ " privetkey L,\n"
+ " phrase ,\n"
+ ");";
stmt.execute(sql);
The line stmt.execute(sql); generates a exception with the message
"org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (near ")": syntax error)"
code:
void test()
{
ted++;
try {
Connection c = null;
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:ted.db");
Statement stmt = null;
stmt = c.createStatement();
String sql;
// this will now through a exception becouse the table allready exist
sql = "CREATE TABLE IF NOT EXISTS exchangesd (\n"
+ " id integer PRIMARY KEY,\n"
+ " name text ,\n"
+ " publickey ,\n"
+ " privetkey L,\n"
+ " phrase ,\n"
+ ");";
stmt.execute(sql); // EXCEPTION GOES OF HEAR
sql = "INSERT INTO exchangesd (name, publickey, privetkey, phrase ) " +
"VALUES ('exchangea', publickkeya, 'privet keya', 'phasea' );";
stmt.executeUpdate(sql);
}catch(Exception e)
{
ted++;
}
}
You have extra , here:
+ " phrase ,\n"
+ ");";
and the SQL parser fails when seeing the following ) when it is syntactically not possible.
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 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] ... ]
I am trying to update a MS Access database. I have searched this and I have tried everything I have found but I am still getting the following error.
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error in UPDATE statement.
Any help would be very helpful. My code is below...;
String sqlStatement = "UPDATE ProductCatalogue"
+ "SET [StockLevel] = ?"
+ "WHERE [ProductID] = ?;";
PreparedStatement prepStatement = connection.prepareStatement(sqlStatement);
prepStatement.setInt(1, quantity);
prepStatement.setInt(2, productID);
//= "UPDATE ProductCatalogue"
//+ "SET StockLevel = " + quantity
//+ "WHERE ProductID = " + productID + ";";
try {
//myStatement.executeUpdate(sqlStatement);
prepStatement.executeUpdate();
} catch (SQLException sqle) {
System.out.println("Oopss...." + sqle);
}
connection.close();
prepStatement.close();
you may need a few whitespaces. Try:
String sqlStatement = "UPDATE ProductCatalogue "
+ "SET [StockLevel] = ? "
+ "WHERE [ProductID] = ?;";
(note the space after ProductCatalogue and the first ?)
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);