java.sql.SQLException: lock wait time out exceeded; try restarting transaction - java

Hi in my project i am have created 2 tables which was Role_header and Role_details tables.
And also Role_details table is referring to the Role_header table.
In my java class i have two method they are
insertRoleHeader(...) --> which will be called first and set conn.setAutoCommit(false).i didn't commit this because following this i want to insert role_details with multiple records in Role_details table. so i will call this method first, if any exceptions thrown. i have set this to rollback in catch.
insertRoleDetails(.....) --> this method will be called by forloop. each and every calling of this method i will commit. at that time i am getting error as java.sql.SQLException: lock wait time out exceeded; try restarting transaction.
my sample code is here:
public void insertHeader(RoleMasterSupport rMS) throws SQLException {
connectDB();
Statement stmt = null;
try {
roleMasterConn.setAutoCommit(false);
stmt = roleMasterConn.createStatement();
String sql = "insert into role_header( create_user, " +
"create_date, " +
"run_user, " +
"run_date, " +
"role_id, " +
"role_name, "+
"remarks) " +
"values('"+Constants.sUserName+"', now(), "
+ "'"+Constants.sUserName+"', now(), "
+ "'"+rMS.getsRoleID()+"', '"+rMS.getsRoleName()+"', "
+ "'"+rMS.getsRemarks()+"') ";
stmt.executeUpdate(sql);
stmt.close();
} catch (SQLException e) {
roleMasterConn.rollback();
throw e;
}
}
public void insertDetails(RoleMasterSupport rMS, TableModel model) throws SQLException
{
for (int i = 0; i < model.getRowCount(); i++) {
dbop.insertDetail(rMS, rMS.getaLScreenNames().get(i),
rMS.getaLAdd().get(i), rMS.getaLView().get(i),
rMS.getaLModify().get(i), rMS.getaLDelete().get(i));
}
}
public void insertDetail(RoleMasterSupport rMS, String sScreenName, String sAdd, String sView, String sModify, String sDelete) throws SQLException
{
connectDB();
Statement stmt = null;
try {
roleMasterConn.setAutoCommit(false);
stmt = roleMasterConn.createStatement();
String sql = "insert into role_details( create_user, " +
"create_date, " +
"run_user, " +
"run_date, " +
"role_id, " +
"screen_name, " +
"modify_screen, " +
"add_screen, " +
"delete_screen, " +
"view_screen) " +
"values('"+Constants.sUserName+"', now(), "
+ "'"+Constants.sUserName+"', now(), "
+ "'"+rMS.getsRoleID()+"', '"+sScreenName+"', "
+ "'"+sModify+"', '"+sAdd+"', "
+ "'"+sDelete+"', '"+sView+"') ";
stmt.executeUpdate(sql);
roleMasterConn.commit();
} catch (SQLException e) {
roleMasterConn.rollback();
throw e;
}
}

Related

sqlite java query does not insert into table

Have sqlite table named good_in with columns in_id, good_code, in_group, in_quantity, in_VATPaid
Here is my table example
and have method to insert records into it
public static void inputGoods(GoodsInput goodsinput){
String goodCode = goodsinput.getInGood().getGood_code();
int goodBatch = goodsinput.getInGroup();
int goodQuantity = goodsinput.getInQuantity();
double goodVATPaid = goodsinput.getInVatPaid();
String sqlInsert = "INSERT INTO good_in (good_code, in_group, in_quantity, in_VATPaid)"
+ " VALUES ('" + goodCode + "', " + "'" + goodBatch + "', " + "'" + goodQuantity
+ "', " + "'" +goodVATPaid + "');";
System.out.print(sqlInsert);
Connection conn = ConnectionFactory.ConnectDB();
try{
Statement statement = conn.createStatement();
statement.executeUpdate(sqlInsert);
}
catch(SQLException e){
}
}
Connection class
public static Connection ConnectDB(){
try{
Class.forName("org.sqlite.JDBC");
Connection con = DriverManager.getConnection("jdbc:sqlite:kahuyq.db");
return con;
} catch (HeadlessException | ClassNotFoundException | SQLException ex){ JOptionPane.showMessageDialog(null, ex); }
return null;
}
When I copy the printed query to sqlite manager it adds the row, but from java it ends program with no error but does not add row to my table.
What is wrong?
Have also other method that checks weather the good_code exists in table good which have only 2 columns id and good_code and if does not exist adds it. this method is accessed from GoodsInput constructor. When I delete the method from constructor the other method works fine.
Here is that method
public static void insertGoods(Good g){
String sqlSelect = "Select * from good where good_code = '"
+ g.getGood_code() + "'" ;
String sqlInsert = "INSERT INTO good (good_code)"
+ "VALUES ('" + g.getGood_code() +"')";
Connection conn = ConnectionFactory.ConnectDB();
try{
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(sqlSelect);
while(!rs.next()){
statement.executeUpdate(sqlInsert);
break;
}
}
catch(SQLException e){
}
}
Try to add
conn.commit();
after the execution of your statement.

How to use question mark PreparedStatement (Java)?

I want to create a java source object in oracle database via JDBC, PreparedStatement. However, in the java source file, there are several question marks. Once I executed it, I faced an error message like below..
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
I changed my code to be more understandable.
private void installOS_COMMAND() {
Connection targetDBconn = null;
PreparedStatement pstmt = null;
Statement stmt = null;
try {
String SQL = "create or replace java source named \"FILE_TYPE_JAVA\" as\n"
+ "public class FileType {\n"
+ " public static String getFileTypeOwner(Connection con) throws Exception {\n"
+ " String sFileTypeOwner = null;\n"
+ " CallableStatement stmt = con.prepareCall(\"begin dbms_utility.name_resolve(?,?,?,?,?,?,?,?); end;\");\n"
+ " stmt.setString(1, \"FILE_TYPE\");\n"
+ " stmt.setInt(2, 7);\n"
+ " stmt.registerOutParameter(3, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(4, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(5, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(6, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(7, oracle.jdbc.OracleTypes.NUMBER);\n"
+ " stmt.registerOutParameter(8, oracle.jdbc.OracleTypes.NUMBER);\n"
+ " stmt.execute();\n"
+ " sFileTypeOwner = stmt.getString(3);\n"
+ " stmt.close();\n"
+ " return sFileTypeOwner;\n"
+ " }\n"
+ "}";
targetDBconn = globalTargetConn.connect();
pstmt = targetDBconn.prepareStatement(SQL);
pstmt.executeUpdate();
} catch (SQLException ex) { logWriter.writeLogs(logTextArea, LogWriter.ERROR, ex.getMessage());
} finally {
if (pstmt != null ) try {pstmt.close();} catch(SQLException ex) {}
if (targetDBconn != null ) try {targetDBconn.close();} catch(SQLException ex) {}
}
}
Is there someone who can fix this problem?
Don't use prepared statements:
private void installOS_COMMAND() {
Connection targetDBconn = null;
Statement stmt = null;
try {
String SQL = "create or replace java source named \"FILE_TYPE_JAVA\" as\n"
+ "public class FileType {\n"
+ " public static String getFileTypeOwner(Connection con) throws Exception {\n"
+ " String sFileTypeOwner = null;\n"
+ " CallableStatement stmt = con.prepareCall(\"begin dbms_utility.name_resolve(?,?,?,?,?,?,?,?); end;\");\n"
+ " stmt.setString(1, \"FILE_TYPE\");\n"
+ " stmt.setInt(2, 7);\n"
+ " stmt.registerOutParameter(3, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(4, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(5, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(6, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(7, oracle.jdbc.OracleTypes.NUMBER);\n"
+ " stmt.registerOutParameter(8, oracle.jdbc.OracleTypes.NUMBER);\n"
+ " stmt.execute();\n"
+ " sFileTypeOwner = stmt.getString(3);\n"
+ " stmt.close();\n"
+ " return sFileTypeOwner;\n"
+ " }\n"
+ "}";
targetDBconn = globalTargetConn.connect();
stmt = targetDBconn.createStatement();
stmt.setEscapeProcessing(false);
stmt.executeUpdate(SQL);
} catch (SQLException ex) { logWriter.writeLogs(logTextArea, LogWriter.ERROR, ex.getMessage());
} finally {
if (targetDBconn != null ) try {targetDBconn.close();} catch(SQLException ex) {}
}
}

SQLITE UPDATE OR INSERT statement doesn't want to execute

public synchronized void saveMatchValue(int photoRecOwner,
int[] photoRecAssign, float[] value) {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
database.beginTransaction();
String sql = " UPDATE " + TypeContract.CTablePhotoMatch.TABLE_NAME
+ " SET " + TypeContract.CTablePhotoMatch.VALUE + "=? "
+ " WHERE " + TypeContract.CTablePhotoMatch.FK_OWNER
+ "=? AND " + TypeContract.CTablePhotoMatch.FK_ASSIGN + "=? ;"
+ " INSERT OR IGNORE INTO "
+ TypeContract.CTablePhotoMatch.TABLE_NAME + "("
+ TypeContract.CTablePhotoMatch.FK_OWNER + ","
+ TypeContract.CTablePhotoMatch.FK_ASSIGN + ","
+ TypeContract.CTablePhotoMatch.VALUE + ") VALUES (?, ?, ?);";
SQLiteStatement stmt = database.compileStatement(sql);
try {
int rows = photoRecAssign.length;
for (int i = 0; i < rows; i++) {
if (photoRecOwner > photoRecAssign[i]) {
stmt.bindLong(1, photoRecOwner);
// stmt.bindLong(index, value)
stmt.bindLong(2, photoRecAssign[i]);
} else {
stmt.bindLong(1, photoRecAssign[i]);
stmt.bindLong(2, photoRecOwner);
}
stmt.bindDouble(3, value[i]);
stmt.execute();
stmt.clearBindings();
}
database.setTransactionSuccessful();
} finally {
stmt.close();
// updtStmt.close();
database.endTransaction();
// database.close();
}
}
Without error and compile-error,
I dont know if the sql statement syntax is correct: concrete the : ; , but without compile errors, the insert and(probably update) command are not executed....
Can I catch some more details?(Of sqlite statemenst) to find out the bug
You can only use SQLiteStatement to execute single statements. The SQL after the ; is not executed.
Split the SQL to execute the statements separately.

Java SQLException on a string that runs in mysql

I am trying to make an inserction of a cliente.
When I print the string from the executeUpdate, copy and paste on mysql, the data is inserted with no problem.
The Exception has the follow description:
Exception in thread "main" 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 'update cliente set honorarioMensal = 2000.2 where cnpj = 'cnpj_ex'' at line 2
Can somebody help me?
public class Teste {
public static void main(String[] args) throws SQLException {
try {
Industria industria = IndustriaDB.getById(1);
System.out.println(industria);
Funcionario funcionario = new Funcionario("Func1","Func1");
funcionario.setCustoMensal(22);
Cliente cliente = new Cliente("cnpj_ex", "nome_ex",industria);
cliente.setPreco((float) 2000.2);
System.out.println(cliente);
System.out.println(cliente.getFuncionario());
ClienteDB.inserir(cliente);
ClienteDB.deletar(cliente);
} catch (ContexataException ge) {
System.out.println("---> " + ge.getMessage());
System.out.println("---> Detalhamento do erro: ");
ge.printStackTrace();
} finally {
}
}
}
public class ClienteDB extends Conexao{
public static void inserir(Cliente cliente) throws ContexataException, SQLException, NullPointerException {
Connection conn = Conexao.getConnection();
try {
String createString =
"INSERT into cliente "
+ "(cnpj, nome, id_Industria) "
+ "values('" + cliente.getCnpj() + "','"
+ cliente.getNome() + "',"
+ cliente.getIndustria().getId() + ");";
if (cliente.getFuncionario() != null){
createString = createString + "\n update cliente set cpf_Funcionario = '" + cliente.getFuncionario().getCpf() + "' where cnpj = '" + cliente.getCnpj() + "';";
}
if (cliente.getPreco() != 0.0){
createString = createString + "\n update cliente set honorarioMensal = " + cliente.getPreco() + " where cnpj = '" + cliente.getCnpj() + "';";
}
System.out.println("SQL: " + createString);
executeUpdate(conn, createString);
System.out.println("Novo cliente inserido!\n");
// } catch (SQLException e) {
// throw new ContexataException("Erro ao inserir novo cliente.");
} catch (NullPointerException e) {
throw new ContexataException("Alguns dados não foram preenchidos suficientemente para o banco de dados!");
} finally {
Conexao.closeAll(conn);
}
}
public class Cliente { // only the atributes are necessary...
private String cnpj;
private String nome;
private float preco;
private Industria industria;
private Funcionario funcionario;
// getter and setter...
The problem is \n characters in the query string. You shouldn't use them, check your code and remove invalid characters.
if (cliente.getFuncionario() != null){
createString = createString + " update cliente set cpf_Funcionario = '" + cliente.getFuncionario().getCpf() + "' where cnpj = '" + cliente.getCnpj() + "';";
}
if (cliente.getPreco() != 0.0){
createString = createString + " update cliente set honorarioMensal = " + cliente.getPreco() + " where cnpj = '" + cliente.getCnpj() + "';";
}
And you can't writeupdate in the insert statements.
You cannot think about your problem like if you were typing the commands in a GUI. You must execute one executeUptade per statement rather than a batch of them. Of course also remove the ; at the end of the statement.
In fact GUIs probably will split your sql sentences and then send them one by one to SQL one by one.

java database function removed - still executing

I have a java web application that I removed a function from the code and yet the database entries that this function writes are still being written to the database.
Inside the IssueWarrant function there is a call to insertWarrantFee that has been commented out.
private void issueWarrant(String CasePrefix, String CaseNumber, String HearingType, String Suspend)
{
int i = 0, intDivision = 0, pos = 0;
String SummSeq = getSummSeq(CasePrefix, CaseNumber);
String Charges = getCharges(CasePrefix, CaseNumber, HearingType);
boolean isVacated = false, isHearingFound = false;
NextBWNumber warrNbr = new NextBWNumber();
String WarrantNumber = warrNbr.getNextBWNumber();
String warrStatus = warrNbr.getNextBWNStatus();
String HearingDesc = "", Division = "";
isVacated = getVacatedStatus(CasePrefix, CaseNumber, HearingType);
isHearingFound = getHearingStatus (CasePrefix, CaseNumber, HearingType);
HearingDesc = getFormatToday() + " " + getHearingDesc(HearingType);
if (HearingDesc.length() > 30)
{
HearingDesc = HearingDesc.substring(0,30);
}
Division = getHearingJudge(CasePrefix,CaseNumber,HearingType);
intDivision = Integer.parseInt(Division);
if (intDivision < 10)
{ Division = "0" + Division; }
Statement localstmt = null;
String localqueryString;
localqueryString = "INSERT INTO " + library7 + "CMPBWPND" +
" (CASPRE, CASNUM, DEFSEQ, CHGSEQ, SUMSEQ, STSCOD, STSDAT," +
" STATUT, CHGABV, BWNBR, JUDCOD, PRVFLG, CT2FLG, DIVISN, BNDAMT," +
" BTYPE, CMNT, CUSER, TUSER, LUPDAT, SCRDAT, STATSDAT, SUMCRDAT, LUPDATE )" +
" VALUES ('" + CasePrefix + "', " + CaseNumber + ", 1, " + Charges.substring(i, i + 1) +
", " + SummSeq + ", 9, " + getShortDate() + ", 'RCP 12-A TA', 'WARRANT', '" +
WarrantNumber + "', " + intDivision + ", 'N', 1, '" + Division + "', " +
BondAmt + ", '" + BondType + "', '" + HearingDesc + "', 'TAAD', 'TAAD', " +
getShortDate() + ", " + getShortDate() + ", " + getLongDate() + ", " + getLongDate() +
", " + getLongDate() + ")";
try
{
if (!isVacated && isHearingFound)
{
localstmt = conn.createStatement();
localstmt.executeUpdate(localqueryString);
localstmt.close();
StatusMsg = "Client No Show-WI";
}
if (isVacated)
{
StatusMsg = "Client Vacated Case";
}
if (!isHearingFound)
{
StatusMsg = "Client Hearing Missing";
}
} catch (SQLException e)
{
System.out.println("IssueWarr - Error in IssueWarrant");
e.printStackTrace();
ReturnInfo = "Issuing Warrants Failed.";
success = false;
}finally
{
try
{
if (!localstmt.isClosed())
{
localstmt.close();
}
} catch (SQLException sql2)
{
System.out.println("Error trying to close connections. Exception: " + sql2.getMessage());
}
}
**//insertWarrantFee(CasePrefix, CaseNumber, SummSeq, WarrantNumber);**
updateHearingRecord(CasePrefix, CaseNumber, HearingType, Charges.substring(i, i + 1), Suspend);
for ( i = 1; i < Charges.length(); i++ )
{
insertBWPTFRecord(CasePrefix, CaseNumber, SummSeq, Charges.substring(i, i + 1));
}
if (!success)
{
StatusMsg = "Client Iss. Warrant Failure";
}
}
Here is the code that the insertWarrantFee called before it was commented out:
private void insertWarrantFee(String CasePrefix, String CaseNumber, String SummSeq, String WarrantNumber)
{
Statement localstmt = null;
String localqueryString;
ResultSet localrSet = null;
String feeAmt = null;
localqueryString = "SELECT AUTO$$ FROM " + library3 + "CMPDKTTP WHERE DKTTYP = 'W'";
try
{
localstmt = conn.createStatement();
localrSet = localstmt.executeQuery(localqueryString);
while (localrSet.next())
{
feeAmt = localrSet.getString("AUTO$$");
}
localstmt.close();
localrSet.close();
} catch (SQLException e)
{
System.out.println("IssueWarr - Error in Insert Warrant Fee SQL1");
e.printStackTrace();
ReturnInfo = "Issuing Warrants Failed.";
success = false;
}finally
{
try
{
if (!localstmt.isClosed())
{
localstmt.close();
}
} catch (SQLException sql2)
{
System.out.println("Error trying to close connections. Exception: " + sql2.getMessage());
}
}
localqueryString = "INSERT INTO " + library7 + "CMPBWTRN"
+ " (CASPRE, CASNUM, DEFSEQ, SUMSEQ, BWNBR, FEEAMT, DKTTYP, TUSER, LUPDAT)"
+ " VALUES ('" + CasePrefix + "', " + CaseNumber + ", 1, " + SummSeq + ", '" + WarrantNumber
+ "', " + feeAmt + ", 'W', 'TAAD', " + getShortDate() + ")";
try
{
localstmt = conn.createStatement();
localstmt.executeUpdate(localqueryString);
localstmt.close();
} catch (SQLException e)
{
System.out.println("IssueWarr - Insert Warrant Fee SQL2");
e.printStackTrace();
ReturnInfo = "Issuing Warrants Failed.";
success = false;
}finally
{
try
{
if (!localstmt.isClosed())
{
localstmt.close();
}
} catch (SQLException sql2)
{
System.out.println("Error trying to close connections. Exception: " + sql2.getMessage());
}
}
}
So even though the line that called insertWarrantFee is commented out a record is still being inserted into CMPBWTRN.
Any ideas how this could happen? The developer is indicating it could be a tomcat connection cache issue? Any other suggestion beside magical code?
Thanks!
Leslie
A couple of things to try:
Make sure you've redeployed the application and have restarted Tomcat. Check the timestamp of the deployed class in question.
Clean Tomcat's tmp and work directories
Open the deployed Java class using a decompiler to see whether the removed code is still in there.
Add a logging (or System.out.println) statement to the method that's commented out, and to the method calling it. See whether one or both are printed after redeploying the changes.

Categories

Resources