Insert sql query not inserting row in db - java

I am inserting a new row in db, there is no exception in the console. But the row is not inserted into the table.
String name = request.getParameter("name");
String city = request.getParameter("city");
String country = request.getParameter("country");
String query = "INSERT INTO `test`.`student`(Name,City,Country)VALUES(?,?,?);";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(query);
ps.setString(1,name);
ps.setString(2,city);
ps.setString(3,country);
ps.executeUpdate();
ps.close();

No need of casting the PreparedStatement again in connecting the query. It should be like
Connection conn = getDBConnection();
PreparedStatement ps = con.prepareStatement(query);
Remove the ; from the query inside the doublequotes
Prefer concatenation operator ( + sign) while using single quotes inside double quoted strings in the query

Here is a sample code that I have tested and working fine. Compare it with your code to know what you are doing wrong.
public void insertRowToDB(int staffID, String first_name, String last_name, int department_ID) {
Connection dbConnection = null;
try {
dbConnection = DatabaseConnection.getconnection();
if (!dbConnection.isClosed()) {
String sql = "INSERT INTO staff (staffID,first_name,last_name,department_ID) VALUES(?,?,?,?)";
PreparedStatement statement = dbConnection.prepareStatement(sql);
statement.setInt(1, staffID);
statement.setString(2, first_name);
statement.setString(3, last_name);
statement.setInt(4, department_ID);
statement.executeUpdate();
}
} catch (SQLException ex) {
Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (dbConnection!=null) {
if (!dbConnection.isClosed()) {
dbConnection.close();
}
}
} catch (SQLException ex) {
Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

A priori view of your code, there is no the commit statement.
You need to perform this statement right before the ps.close() line.
Best regards!

Related

Getting error "statement.executeupdate() cannot issue statements that produce result sets." when trying to insert into mysql using JDBC

I'm trying to get the primary auto incremented key from one table and store this in another using MySQL connector and JDBC. Although its giving me this error:
statement.executeupdate() cannot issue statements that produce result
sets.
I think its something to do with the storing of the integer variable but not too sure.
public void insertIntoWorkoutLogs(String field_setNumber, String field_repNumber, String field_weightAmount) {
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/workout","root","");
Statement statement =connection.createStatement();
String insert ="INSERT INTO `workout`.`workoutlogs`" + " (`SetNumber`, `RepNumber` , `WeightAmount`)"
+ "VALUES('" +field_setNumber+"','"+field_repNumber+"','"+field_weightAmount+"')";
statement.executeUpdate(insert);
int workoutID = insertQueryGetId("SELECT workoutID FROM workout");
String insert2 ="INSERT INTO `workout`.`workoutlogs`" + " (`WorkoutID`)"
+ "VALUES('" +workoutID+"')";
statement.executeUpdate(insert2);
connection.close();
}catch(Exception e) {
System.out.println(e);
}
}
public int insertQueryGetId(String query) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/workout","root","");
Statement statement =connection.createStatement();
int workoutID=0;
int result=-1;
try {
workoutID = statement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = statement.getGeneratedKeys();
if (rs.next()){
result=rs.getInt(1);
}
rs.close();
statement.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
I've tried using statement for this, but I'm thinking it may have to be prepared statement for it to work. Expecting to store the auto incremented primary key of one table (workouts) into a field within another table (workoutlogs).
It's because you are passing wrong query. Statement.RETURN_GENERATED_KEYS works with Insert queries not with Select queries.
When you insert a row in database, an auto increment value gets generated and is returned but you are passing a Select statement
As Syed Asad Manzoor said, it will work for you but then you need to remove Statement.RETURN_GENERATED_KEYS and statement.executeQuery() has return type of ResultSet so you need to store the result in ResultSet only.
public void insertIntoWorkoutLogs(String field_setNumber, String field_repNumber, String field_weightAmount) {
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/workout","root","");
Statement statement =connection.createStatement();
String insert ="INSERT INTO `workout`.`workoutlogs`" + " (`SetNumber`, `RepNumber` , `WeightAmount`)"
+ "VALUES('" +field_setNumber+"','"+field_repNumber+"','"+field_weightAmount+"')";
statement.executeUpdate(insert);
**int workoutID = insertQueryGetId("SELECT workoutID FROM workout");** // Line of Concern 1
String insert2 ="INSERT INTO `workout`.`workoutlogs`" + " (`WorkoutID`)"
+ "VALUES('" +workoutID+"')";
statement.executeUpdate(insert2);
connection.close();
}catch(Exception e) {
System.out.println(e);
}
}
public int insertQueryGetId(String query) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/workout","root","");
Statement statement =connection.createStatement();
int workoutID=0;
int result=-1;
try {
// Line of Concern 2
**workoutID = statement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);**
In line (marked as Line of Concern 1 ..
int workoutID = insertQueryGetId("SELECT workoutID FROM workout"); you are passing query as "SELECT...." and at point marked as Line of Concern 2
workoutID = statement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS); you are using executeUpdate.. thats why exception is thrown.
Change statement.executeUpdate(query) to statement.executeQuery(query)..
The INSERT statement needs to have flag RETURN_GENERATED_KEYS.
Then getting the ResultSet would deliver for every insert record the generated key(s).
Also use a PreparedStatement for escaping of strings and against SQL injection.
Use try-with-resources to automatically close the several objects, even with exception or early return.
Class.forName("com.mysql.cj.jdbc.Driver");
try (Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/workout", "root", "")) {
String insertSql = "INSERT INTO `workout`.`workoutlogs`"
+ " (`SetNumber`, `RepNumber` , `WeightAmount`)"
+ " VALUES(?, ?, ?)";
try (PreparedStatement statement = connection.prepareStatement(insertSql,
Statement.RETURN_GENERATED_KEYS)) {
statement.setString(field_setNumber);
statement.setString(field_repNumber);
statement.setBigDecimal(field_weightAmount);
statement.executeUpdate();
try (ResultSet rs = statement.getGeneratedKey()) {
if (rs.next()) {
int workoutID = rs.getInt(0);
//... second insert here
}
}
}
}

How can I load a XML file to an XMLType column on Oracle 18c with java

I have a complex directory system with millions of xml files which i need to retrieve to an XMLType column in Oracle 18c. I'm working with a java method that is executed by a procedure to re-load this files on this particular table. Since a lot of the of the java libraries were deprecated i'm out of options to solve this issue. The way I had finded to workaround was a tempory table with a CLOB column where I can insert the content from the files and than inside oracle I insert those in the original table using a XMLType(clobVariable). BUT, it doesnt work on files larger then 20k characters.
If anyone can help me I'm more than glad to give more information.
(I'm from Brazil and maybe I didn't made myself clear on the explanation btw)
public static void inserirXml() throws Exception{
try {
int num_id_nfe;
String dirArquivo = "";
String query;
String queryUpdate;
String reCheck, insert;
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:default:connection:");
conn.setAutoCommit(false);
query = "SELECT ID_NFE, DSC_CAMINHO_XML FROM DFE_NFE_CAMINHO_XML WHERE FLG_CARREGADO = 0 AND ROWNUM <= 1000";
Statement stmt = conn.createStatement();
Statement stmt2 = conn.createStatement();
Statement stmt3 = conn.createStatement();
Statement stmt4 = conn.createStatement();
stmt.executeQuery(query);
ResultSet rset = stmt.getResultSet();
while(rset.next() == true) {
try {
num_id_nfe = rset.getInt(1);
dirArquivo = rset.getString(2);
byte[] bytes = Files.readAllBytes(Paths.get(dirArquivo));
String xmlString = new String(bytes, "utf-8");
String insertQuery = "INSERT INTO DFE_NFE_REP_XML_TMP (ID_NFE, XMLCLOB) VALUES(?,?)";
PreparedStatement pstmt = conn.prepareStatement(insertQuery);
xmlString = xmlString.substring(1);
pstmt.setInt(1, num_id_nfe);
pstmt.setNString(2, xmlString);
pstmt.execute();
pstmt.close();
queryUpdate = "UPDATE DFE_NFE_CAMINHO_XML SET FLG_CARREGADO = 1 WHERE ID_NFE = " + num_id_nfe + " \n";
stmt2.executeQuery(queryUpdate);
}catch(SQLException e) {
System.err.println(e.getMessage()+" loop");
stmt2.close();
throw e;
}
}
insert = "INSERT INTO DFE_NFE_REP_XML (ID_NFE, CONTEUDO) SELECT ID_NFE, XMLType(XMLCLOB) FROM DFE_NFE_REP_XML_TMP";
stmt4.executeUpdate(insert);
reCheck = "UPDATE DFE_NFE_CAMINHO_XML SET FLG_CARREGADO = 0 WHERE id_nfe not in (select id_nfe from dfe_nfe_rep_xml) and flg_carregado = 1";
stmt3.executeQuery(reCheck);
conn.commit();
rset.close();
stmt.close();
stmt2.close();
stmt3.close();
stmt4.close();
conn.close();
} catch (SQLException x) {
System.err.println(x.getMessage()+" geral");
}catch (ClassNotFoundException y) {
throw y;
}catch(Exception z) {
throw z;
}
}

Rollback does not work

I want to rollback all records have been inserted to table when exception occurs.
but conInsert.rollback() doesn't work.
Maybe I miss some code?
Here is my code
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(connectionUrl);
//con.setAutoCommit(false);
Statement st = con.createStatement();
String querySelectOrderInTp = "SELECT order_in_tp_id, order_in_tp_qty, order_in_tp_price, order_in_tp_article_tc_id, order_in_tp_warehouse_tc_id, inv_stock_tp_id, inv_stock_tp_qty_available from order_in_tp LEFT JOIN inv_stock_tp on(order_in_tp_warehouse_tc_id=inv_stock_tp_whouse_current_id AND order_in_tp_article_tc_id=inv_stock_tp_article_tc_id AND order_in_tp_price=inv_stock_tp_price) where order_in_tp_pick_up_timestamp = 'A' AND order_in_tp_date = '2013-06-11' GROUP BY order_in_tp_id;";
ResultSet rs = st.executeQuery(querySelectOrderInTp);
String queryUpdateInvStockTp = "INSERT INTO inv_stock_tp (cre_tms,upd_tms,cre_usr,upd_usr,version,usr_act,inv_stock_tp_id,inv_stock_tp_key, inv_stock_tp_whouse_current_id,inv_stock_tp_article_tc_id,inv_stock_tp_qty_available,inv_stock_tp_qty_min,inv_stock_tp_price) VALUES (NOW(),NOW(),'demo2','demo2',1,'A',null,'AAAA',?,?,?,0,2000.0000)";
conInsert = DriverManager.getConnection(connectionUrl);
conInsert.setAutoCommit(false);
ps = conInsert.prepareStatement(queryUpdateInvStockTp);
String queryUpdateOrderInTp = "UPDATE order_in_tp set order_in_tp_pick_up_timestamp = ? WHERE order_in_tp_id = ?";
psUpdate = con.prepareStatement(queryUpdateOrderInTp);
while(rs.next()) {
Integer qty = rs.getInt(7) - rs.getInt(2);
ps.setString(1, rs.getString(5));
ps.setString(2, rs.getString(4));
ps.setString(3, rs.getString(2));
ps.execute();
psUpdate.setString(1, "A");
psUpdate.setString(2, rs.getString(1));
psUpdate.execute();
ps.clearParameters();
psUpdate.clearParameters();
}
conInsert.commit();
} catch (Exception e) {
e.printStackTrace();
if (conInsert != null) {
try {
System.err.print("Transaction is being rolled back");
conInsert.rollback();
} catch (SQLException excep) {
excep.printStackTrace();
}
}
}
I make an exception in last record but all record before it still have been inserted.
By default, MySQL runs with autocommit mode enabled. This means that as soon as you execute a statement that updates (modifies) a table, MySQL stores the update on disk to make it permanent. I dont know java, but make sure that You have the START TRANSACTION statement, and then COMMIT or ROLLBACK.

Problems with PreparedStatement - Java

Im trying to use PreparedStatement to my SQLite searches. Statement works fine but Im getting problem with PreparedStatement.
this is my Search method:
public void searchSQL(){
try {
ps = conn.prepareStatement("select * from ?");
ps.setString(1, "clients");
rs = ps.executeQuery();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
but Im getting this error:
java.sql.SQLException: near "?": syntax error at
org.sqlite.DB.throwex(DB.java:288) at
org.sqlite.NestedDB.prepare(NestedDB.java:115) at
org.sqlite.DB.prepare(DB.java:114) at
org.sqlite.PrepStmt.(PrepStmt.java:37) at
org.sqlite.Conn.prepareStatement(Conn.java:231) at
org.sqlite.Conn.prepareStatement(Conn.java:224) at
org.sqlite.Conn.prepareStatement(Conn.java:213)
thx
Columns Parameters can be ? not the table name ;
Your method must look like this :
public void searchSQL()
{
try
{
ps = conn.prepareStatement("select * from clients");
rs = ps.executeQuery();
}
catch (SQLException ex)
{
ex.printStackTrace();
}
}
Here if I do it like this, it's working fine, see this function :
public void displayContentOfTable()
{
java.sql.ResultSet rs = null;
try
{
con = this.getConnection();
java.sql.PreparedStatement pstatement = con.prepareStatement("Select * from LoginInfo");
rs = pstatement.executeQuery();
while (rs.next())
{
String email = rs.getString(1);
String nickName = rs.getString(2);
String password = rs.getString(3);
String loginDate = rs.getString(4);
System.out.println("-----------------------------------");
System.out.println("Email : " + email);
System.out.println("NickName : " + nickName);
System.out.println("Password : " + password);
System.out.println("Login Date : " + loginDate);
System.out.println("-----------------------------------");
}
rs.close(); // Do remember to always close this, once you done
// using it's values.
}
catch(Exception e)
{
e.printStackTrace();
}
}
Make ResultSet a local variable, instead of instance variable (as done on your side). And close it once you are done with it, by writing rs.close() and rs = null.
Passing table names in a prepared statement is not possible.
The method setString is when you want to pass a variable in a where clause, for example:
select * from clients where name = ?
thx for replies guys,,,
now its working fine.
I noticed sql query cant hold ? to columns too.
So, this sql query to PreparedStatement is working:
String sql = "select * from clients where name like ?";
ps = conn.prepareStatement(sql);
ps.setString(1, "a%");
rs = ps.executeQuery();
but, if I try to use column as setString, it doesnt work:
String sql = "select * from clientes where ? like ?";
ps = conn.prepareStatement(sql);
ps.setString(1, "name");
ps.setString(2, "a%"):
rs = ps.executeQuery();
Am I correct? or how can I bypass this?
thx again

How do you access the value of an SQL count () query in a Java program

I want to get to the value I am finding using the COUNT command of SQL. Normally I enter the column name I want to access into the getInt() getString() method, what do I do in this case when there is no specific column name.
I have used 'AS' in the same manner as is used to alias a table, I am not sure if this is going to work, I would think not.
Statement stmt3 = con.createStatement();
ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) FROM "+lastTempTable+") AS count");
while(rs3.next()){
count = rs3.getInt("count");
}
Use aliases:
SELECT COUNT(*) AS total FROM ..
and then
rs3.getInt("total")
The answers provided by Bohzo and Brabster will obviously work, but you could also just use:
rs3.getInt(1);
to get the value in the first, and in your case, only column.
I would expect this query to work with your program:
"SELECT COUNT(*) AS count FROM "+lastTempTable+")"
(You need to alias the column, not the table)
I have done it this way (example):
String query="SELECT count(t1.id) from t1, t2 where t1.id=t2.id and t2.email='"r#r.com"'";
int count=0;
try {
ResultSet rs = DatabaseService.statementDataBase().executeQuery(query);
while(rs.next())
count=rs.getInt(1);
} catch (SQLException e) {
e.printStackTrace();
} finally {
//...
}
<%
try{
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bala","bala","bala");
if(con == null) System.out.print("not connected");
Statement st = con.createStatement();
String myStatement = "select count(*) as total from locations";
ResultSet rs = st.executeQuery(myStatement);
int num = 0;
while(rs.next()){
num = (rs.getInt(1));
}
}
catch(Exception e){
System.out.println(e);
}
%>
Statement stmt3 = con.createStatement();
ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) AS count FROM "+lastTempTable+" ;");
count = rs3.getInt("count");
It's similar to above but you can try like
public Integer count(String tableName) throws CrateException {
String query = String.format("Select count(*) as size from %s", tableName);
try (Statement s = connection.createStatement()) {
try (ResultSet resultSet = queryExecutor.executeQuery(s, query)) {
Preconditions.checkArgument(resultSet.next(), "Result set is empty");
return resultSet.getInt("size");
}
} catch (SQLException e) {
throw new CrateException(e);
}
}
}

Categories