private final static String INSERT = "INSERT INTO electric_usage" +
"(objId, useTime, name, usage) " +
"VALUES (?, ?, ?, ?)";
public static boolean insertUsage(int index, Timestamp time, String name, double usage) {
Connection con = null;
try {
con = DBManager.getInstance().getConnection();
PreparedStatement stmt = con.prepareStatement(INSERT);
java.util.Date today = new java.util.Date();
stmt.setInt(1, index);
stmt.setTimestamp(2, time);
stmt.setString(3, name);
stmt.setDouble(4, usage);
stmt.addBatch();
stmt.executeBatch();
stmt.close();
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
DBManager.getInstance().close();
}
return true;
}
make INSERT query like this but this code occur syntax error
other load query is work fine only this INSERT quert occur error
im trying to INSERT query in console it occur same error
my query is wrong?
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 'usage) VALUES (192, '2015-09-10 13:55:57', 'test', 0.0045196452704869055)' at line 1
table is
objId(int length 8 not null)
useTime(timestamp length 0 not null)
name (varchar length 255 not null)
usage (double length 11 not null)
index is a reserved word so you should not use it to name a column. List of reserved words here: http://dev.mysql.com/doc/refman/5.6/en/keywords.html
That's because your column names index/usage are all MySQL Reserve words and so needs to be escaped using backtique like below
INSERT INTO electric_usage (`index`, `time`, `name`, `usage`)
Always avoid using table/column name as reserve word else you will have to suffer likewise. Use proper naming convention like prefix t_ for table names and c_ for column names.
index is reserved word in mysql you can't use mysql reserved words.when you write query in query browser than reserved words shows in blue. so please take care about this.if you write query in java coding directly you can't find these type of issues.
Related
While trying to insert a record in the sql table I am using 10 variables for 10 columns in the table, but as when I run the query it throws an error. I have tried looking if there is any typo in my code but can't find any:
Exception in thread "main" java.sql.SQLSyntaxErrorException: 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 '','2019','12','3','10660','2018-12-11','UTC',''{"sleepIQScore": {"min": 0, "max"' at line 1
My code is:
public void insertDataTable1() throws SQLException {
connection = new MyConnection().getConnection();
Random random = new Random();
String timeZone = "UTC";
String dummyJson = "'{\"sleepIQScore\": {\"min\": 0, \"max\": 0, \"sum\": 0, \"count\": 0}}')";
int longestSessionDuration = 1000 + random.nextInt(9999), bamUserID = 1000000 + random.nextInt(9999999);
int year = 2019, month = 12, sleepSessionCount =3;
java.sql.Date longestSessionStart = new java.sql.Date(Calendar.getInstance().getTime().getTime());
String sql = "INSERT INTO aggregates_all_time(bam_user,year,month,sleep_session_count," +
"longest_session_total_duration,longest_session_start,timezone, current_stats, second_longest_session_stats, prior_stats)"
+ "VALUES ("+bamUserID+"','"+year+"','"+month+"','"+sleepSessionCount+"','"+longestSessionDuration+"','" +
""+longestSessionStart+"','"+timeZone+"','"+dummyJson+" ','"+dummyJson+"','"+dummyJson+")";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
int i = preparedStatement.executeUpdate();
System.out.println(i + " Row/s inserted");
}
You should never concatenate values into a query string like this. It is unsafe because it opens your application to SQL injection which is one of the major causes of security issues. In addition, it leads to bugs like your question because of missing quotes, etc.
However, the solution is not to add those missing quotes, because that still leaves you open to SQL injection risks. Instead, you need to use parameters and set the values for those parameters before execution.
A reduced example based on the query in your question:
try (PreparedStatement preparedStatement = connection.prepareStatement(
"INSERT INTO aggregates_all_time(bam_user, year, month, ..) values (?, ?, ?, ..)")) {
preparedStatement.setInt(bamUserID);
preparedStatement.setInt(year);
preparedStatement.setInt(month);
// other values
preparedStatement.executeUpdate();
}
See also Using Prepared Statements in the JDBC tutorial.
Here is the code:
String sqlstatment = "INSERT INTO order (orderedBy, totalItems, totalPrice) "+
"VALUES (?, ?, ?);";
ResultSet keys = null;
try (
PreparedStatement stmt = conn.prepareStatement(sqlstatment, Statement.RETURN_GENERATED_KEYS);
){
stmt.setInt(1, 1);
stmt.setInt(2, 3);
stmt.setInt(3, 5);
int affected = stmt.executeUpdate();
if (affected == 1){
keys = stmt.getGeneratedKeys();
keys.next();
int newKey = keys.getInt(1);
orderBean.setOrderID(newKey);
}else{
System.out.println("An Error has ocurred while creating the Order.");
}
}catch (SQLException e){
System.err.println(e.getMessage());
}finally{
if (keys != null) keys.close();
}
And when I run the code I get this error:
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 'order (orderedBy, totalItems, totalPrice) VALUES (1, 3, 5)' at line 1
I'm not entirely sure why I get the error so if you know that would be great.
order is a reserved word, try
String sqlstatment = "INSERT INTO \"order\" (orderedBy, totalItems, totalPrice) "+
"VALUES (?, ?, ?);";
Your query contains a RESERVED KEYWORD order as your table name. MySQL documentation clearly suggests that use of such keywords should always be avoided, if they need to be used then it has to be with the use of backticks as shown below '`'.
Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.
If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.
Your query that gets assigned to a String in turn should be changed to the following to resolve this error!
"INSERT INTO \"order\" (orderedBy, totalItems, totalPrice) VALUES (?, ?, ?);"
The following is a documentation link to the reserved keywords for MySQL -> Documentation
Hope this helps!
I have a program that selects from a database given a table and column string.
public void selectAllFrom(String table, String column){
String sql = "SELECT ? FROM ?";
try (Connection conn = this.connect();
PreparedStatement pstmt = conn.prepareStatement(sql)){
pstmt.setString(1, column);
pstmt.setString(2, table);
ResultSet rs = pstmt.executeQuery();
while (rs.next()){
System.out.println(rs.getString(column));
}
} catch (SQLException e){
System.out.println(" select didn't work");
System.out.println(e.getMessage());
}
}
For some reason it is not working and it is going right to catch
Here is the connect() function as well:
private Connection connect(){
Connection conn = null;
// SQLite connection string
String url = "jdbc:sqlite:C:/sqlite/db/chinook.db";
try{
// creates connection to the database
conn = DriverManager.getConnection(url);
System.out.println("Connection to SQLite has been established");
} catch (SQLException e){
System.out.println(e.getMessage());
System.out.println("Connection didn't work");
}
return conn;
}
I know the problem is not with the database because I'm able to run other select queries without parameters. It is the parameters that are giving me the problem. Can anyone tell what the problem is?
A table or column name can't be used as a parameter to PreparedStatement. It must be hard coded.
String sql = "SELECT " + column + " FROM " + table;
You should reconsider the design so as to make these two constant and parameterize the column values.
? is a place holder to indicate a bind variable. When a SQL statement is executed, database first checks syntax, and validates the objects being referenced, columns and access permission for specified objects (i.e metadata about objects) and confirms that all are in place and valid. This stage is called parsing.
Post parsing, it substitutes bind variables to query and then proceeds for actual fetch of results.
Bind variables can be substituted in any place in query to replace an actual hard coded data/strings, but not the query constructs them selves. It means
You can not use bind variables for keywords of sql query (ex: SELECT, UPDATE etc.)
You can not use bind variables for objects or their attributes (i.e table names, column names, functions, procedures etc.)
You can use them only in place of a otherwise hard coded data.
ex: SELECT FIRST_NAME, LAST_NAME, 'N' IS_DELETED FROM USER_DATA WHERE COUNTRY ='CANADA' AND VERIFIED_USER='YES'
In above sample query, 'N','CANADA' and 'YES' are the only strings which can be replaced by a bind variable, not any other word.
Using bind variable is best practice of coding. It improves query performance (when used with large no. of queries in tuned database products like Oracle or MSSQL) and also protects your code against sql injection attacks.
Constructing query by concatenating strings (especially data part of query) is never recommended way. You can still construct a query by concatenation for other parts like table name or column name as long as those strings are not directly taken from input.
Below example is acceptable:
query = "Select transaction_id, transaction_date from ";
if (isHistorical(reportType)
{ query = query + "HISTORY_TRANSACTIONS" ;}
else
{query = query + "PRESENT_TRANSACTIONS" ; }
recommended practice is to use
String query_present = "SELECT transaction_id, transaction_date from PRESENT_TRANSACTIONS";
String query_historical = "SELECT transaction_id, transaction_date from HISTORY_TRANSACTIONS";
if (isHisotrical(reportType))
{
ps.executeQuery(query_historical);
}else{
ps.executeQuery(query_present);
}
Is this query possible on java?
"BEGIN;"
+ "INSERT INTO product(code, name, description, category_id) "
+ "VALUES(?,?,?,?);"
+ "INSERT INTO inventory_item(quantity, price, product_id) "
+ "VALUES(?,?,LAST_INSERT_ID());"
+ "COMMIT;";
I used it on a PreparedStatement and it really eating my time just to figure out the error my dbUnit said there is an error on the statement
com.example.dao.exception.DataAccessException:
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 'INSERT INTO product(code, name, description,
category_id) VALUES('00003','lemon ' at line 1
at
com.example.dao.InventoryDaoImpl.addInventoryItem(InventoryDaoImpl.java:126)
I can't print the PreparedStatement on the console I tried
PreparedStatement statement =
connection.prepareStatement( FIND_INVENTORY_ITEM_BY_PRODUCT_CODE_QUERY );
System.out.print( statement );
Can you guys give me a hand figure out the error?
May not be the way, but this has always worked for me:
List<String> sqlStatements = new ArrayList<String>();
// stuff your statements into this list
// (I'm often reading them from some file. The file often
// contains blank lines, comments and semicolons, which I
// strip out.)
Statement stmt = null;
try {
dbConn.setAutoCommit(false);
stmt = dbConn.prepareStatement();
for ( String sql : sqlStatements ) {
logger.debug("\t"+sql);
stmt.addBatch(sql);
}
stmt.executeBatch();
dbConn.commit();
} catch ( Exception e ) {
// handle exceptions
} finally {
// close statement
}
I'm having a problem with setting up a PreparedStatement to insert a new row into my table. I've tested the query in my SQL editor and it worked succesfully but I can't get this PreparedStatement to work.
String sql = "INSERT INTO table game(gamedate, type, world) values (TIMESTAMP '?', ?, '?');"
runQuery(sql, date, type, world);
...
protected runQuery(String sql, Object... params){
try {
initiateConnection();
PreparedStatement statement = connection.PrepareStatement(sql);
int i = 1;
for (Object p : params){
statement.setObject(i, p);
i++;
}
statement.executeUpdate();
} catch (Exception ex){
} finally {
//close up things
}
}
I added in some println() to test the output and it seemed to all be pretty okay
sql: INSERT INTO game(gamedate, type, world) values(TIMESTAMP '?', ?, '?');
date: 2012-03-13 21:42:14
type: 1
world: test
The error I get is
java.sql.SQLException invalid column index
I'm really quite stumped here. Any idea what's the culprit here?
Two guesses:
you don't need quotes around the question marks. Get rid of those
the TIMESTAMP function might be problematic. Try converting the date to a timestamp before setting it in the prepared statement. (date.getTime() / 1000)
Your SQL statement has only one substitutable placeholder. The ones in single quotes are literal question marks.