MySql inserting on multiple table using BEGIN and COMMIT java - java

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
}

Related

Error in the syntax of the SQL insert query using variables

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.

Struts2: Save SQL query in the database

In my Struts2 Java web application users are allowed to query the database. As an example, the user needs to get the employee details whose first name is equal to 'Charles'. Then s/he can select the report columns and criteria (firstname='Charles').
Once the user gives above inputs it need to save the relevant SQL query into the database.
e.g. SQL -> SELECT * FROM employee WHERE firstname='Charles'
Here is what I am trying in my action class.
try {
connection = DriverManager.getConnection(
SelectAction.getDatabase(), SelectAction.getUser(),
SelectAction.getPassword());
if (connection != null) {
System.out.println("Database connection established!");
stmt = connection.createStatement();
String sql = "INSERT INTO reports (report_id, sql) values ('" + reportId + "', '" + sqlQ + "');";
System.out.println("sql--->" + sql);
// Executing query
stmt.executeQuery(sql);
return SUCCESS;
} else {
System.out.println("----Failed to make connection!");
return ERROR;
}
} catch (SQLException e) {
System.out.println("Connection Failed!!");
e.printStackTrace();
return SUCCESS;
}
This is my insert query.
INSERT INTO reports (report_id, sql) values ('mynewreport', 'SELECT * FROM employee WHERE firstname='Charles'');
I am getting following error in my console.
ERROR: syntax error at or near "Charles"
I think here I am using a String so that the problem is with quotes('). I am using postgreSQL as database.
Any suggestions to solve this issue ?
Never use string concatenation of user supplied values to build a SQL statement.
Never use string concatenation of any non-integer values to build a SQL statement.
You will leave yourself open to SQL Injection attacks and/or SQL statement errors.
Hackers will love you for allowing them to steal all your data, and the nefarious ones will corrupt or delete all your data, while laughing maniacally at you on their way to the bank.
Use PreparedStatement and parameter markers.
String sql = "INSERT INTO reports (report_id, sql) values (?, ?)";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, reportId);
stmt.setString(2, sqlQ);
stmt.executeUpdate();
}

JAVA mysql INSERT error

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.

Accessing database with sqlite in Java

I am trying to access a database to then insert new data, but the code below gives me this output:
Opened database successfully
java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database ()
The database is created in a different class, I still get this error whether the database has already been created or not.
What would be causing this error?
Statement stmt = null;
Connection c = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:src/test.db");
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "INSERT INTO table_one (id, name) VALUES (Null, 'Hayley');";
stmt.executeUpdate(sql);
System.out.println("Inserted records");
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Table created sucessfully");
How about not inserting the null value in the id column. It is of no use to insert null value. It might have generated the sql exception. Try INSERT INTO table_one (name) VALUES ('Hayley');.
I would suggest to use PreparedStatement instead of Statement because of the threat of SQL injection.
Sometimes, the particular sql exception can occur if the database name is not given. Have you tried writing the database name like INSERT INTO database_name.table_one (name) VALUES ('Hayley');.

org.postgresql.util.PSQLException: ERROR: syntax error near «,» in Java

The below is the query generate by a prepareStatement in Java:
insert into schema.table(cedula, actividad, mercado, venta_mensual, fortalezas, crecer,
financiamiento, monto, patente, contador, regimen_tri, problemas, bn_servicios, cursos )
values ('val', 'GAM', 'GAM', '0', 'Calidad', 'Sí', 'Sí', '122', 'Sí', 'Sí', 'ddd', 'aaa','ccc', 'bbb' )
The Java code is:
try {
PreparedStatement pstmt = conexion.prepareStatement(query);
pstmt.setString(1, n.getCedula());
//the rest of the sets of the statement continue here from 1 to 13
pstmt.executeUpdate();
conexion.createStatement().execute(query);
return true
} catch (SQLException e) {
e.printStackTrace(); // This error
return false;
}
The query is executed int the try statement and insert the values properly in the DB, BUT it also throws the below exception, at line 192: here 'val':
org.postgresql.util.PSQLException: ERROR: error de sintaxis en o cerca de «,»
org.postgresql.util.PSQLException: ERROR: syntax error near ',' java
The error trace relate to postgres is here:
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:500)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:374)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:366)
By the way, the table has a bigserial value and all the others values showed in the query. Thanks in advance!
If the query contains string constant within the values clause, as you have shown in the question:
query = "insert into table(cedula, actividad, mercado) "
+ " values ('val', 'GAM', 'GAM' )";
then this part of code will work fine:
conexion.createStatement().execute(query);
however this part of code won't work:
pstmt.setString(1, n.getCedula());
//the rest of the sets of the statement continue here from 1 to 13
It will throw an PSQLException: The column index is out of range: X, number of columns: 0, because PreparedStatement.setXXX methods expect placeholders ? in the SQL statement.
On the other hand, when the insert statement contains placeholders (I assume that your INSERT does contain placeholders, because you haven't got the above exception):
query = "insert into tabla(cedula, actividad, mercado) "
+ " values ( ?, ?, ? )";
then pstmt.setString... statements will work fine, however this statement:
conexion.createStatement().execute(query);
will throw an exception: PSQLException: ERROR: syntax error near ','
If your intent is to execute the INSERT twice, the first one using placeholders, and the second one using string values, you must do it in this way:
query1 = "insert into tabla(cedula, actividad, mercado) "
+ " values ('val', 'GAM', 'GAM' )";
query2 = "insert into tabla(cedula, actividad, mercado) "
+ " values ( ? , ? , ? )";
PreparedStatement pstmt = conexion.prepareStatement(query2);
pstmt.setString(1, n.getCedula());
//the rest of the sets of the statement continue here from 1 to 13
pstmt.executeUpdate();
conexion.createStatement().execute(query1);
String sql="INSERT INTO travel values(Source,Destination,VehicleType,PhoneNo)"
+" VALUES ('Mysore','Chennai','l',94400000)";

Categories