How to use question mark PreparedStatement (Java)? - 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) {}
}
}

Related

sql Command has not properly ended

I'm using sql developer and netbeans when ever i try to insert data into the table this error "sql Command has not properly ended".
This is what i tried.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
dbconnection db = new dbconnection();
try {
db.connect();
db.stm = db.con.createStatement();
int result = db.stm.executeUpdate(
"insert into payment values'" + txt_paymentid.getText() + "','" + txt_reservation.getText() +"',
" + "'"+txt_fname.getText()+"',
'"+txt_lname.getText()+"' ,'"+txt_roomid.getText()+"' ,'"+txt_rate.getText()+"' ," + " '"+((JTextField)txt_datein.getDateEditor().getUiComponent()).getText()+"' ,"
+ "'"
((JTextField
)txt_dateout.getDateEditor().getUiComponent()).getText() + "'," + "'" + txt_days.getText() + "','" + txt_payment.getText() + "','" + txt_balance.getText() + "'"
);
if (result > 0) {
JOptionPane.showMessageDialog(this, "Data has been saved succesfully");
} else {
JOptionPane.showMessageDialog(this, "no data has been saved");
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(this, e.toString());
}
}
For a start
The sql should be in the ()
executeUpdate()("insert...
->
executeUpdate("insert...)
second it looks like the insert command itself it not valid
insert into table values (' ....

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

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;
}
}

SQLite java.lang.NullPointerException in only select query

i added sqlite-jdbc-3.7.2.jar to build path. I used insert query. when i opened the wellec.db with notepad, i can see records. But my select is not working.
HERE WellInfo class properties
public Integer wellID;
public Integer measurement;
public String wellname;
public Integer wellstatus;
public String licenseno;
public String gl;
public String kb;
public String spuddate;
public String drillingenddate;
public String totaldepth;
public String notes;
public String easting;
public String northing;
public String coordinatesystem;
public Integer islogadd;
here is my createtable sql
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:wellec.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS WELLINFO " +
"(ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ," +
" WELLNAME CHAR(90) NOT NULL, " +
" WELLSTATUS INT NOT NULL," +
" MEASUREMENT INT NOT NULL," +
" ISLOGADD INT NOT NULL," +
" GL CHAR(50) NOT NULL, " +
" KB CHAR(50) NOT NULL, " +
" SPUDDATE CHAR(50) NOT NULL, " +
" TOTALDEPTH CHAR(50) NOT NULL, " +
" LICENSENO CHAR(50) NOT NULL, " +
" DRILLINGENDDATE CHAR(50) NOT NULL, " +
" NOTES CHAR(150) NOT NULL, " +
" EASTING CHAR(50) NOT NULL, " +
" NORTHING CHAR(50) NOT NULL, " +
" COORDINATESYSTEM CHAR(50) NOT NULL)";
stmt.executeUpdate(sql);
...//other tables sql and stmt.executeUpdate(sql)
stmt.close();
c.commit();
here is my insert query which is working. WellInfo wi as parameter
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:wellec.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "INSERT INTO WELLINFO " +
"(ID, WELLNAME, WELLSTATUS , MEASUREMENT, ISLOGADD , GL, KB, SPUDDATE, TOTALDEPTH, " +
"LICENSENO , DRILLINGENDDATE, NOTES, EASTING, NORTHING, COORDINATESYSTEM) " +
"VALUES (NULL,'" + wi.wellname + "'," + wi.wellstatus + "," + wi.measurement + "," +
"" + wi.islogadd +",'" + wi.gl + "','" + wi.kb + "','" + wi.spuddate + "'," +
"'" + wi.totaldepth + "','" + wi.licenseno + "','" + wi.drillingenddate + "', " +
"'" + wi.notes + "','" + wi.easting + "','" + wi.northing + "','" + wi.coordinatesystem + "');";
stmt.executeUpdate(sql);
stmt.close();
c.commit();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Records created successfully");
return 0;
here is my select
Connection c = null;
Statement stmt = null;
WellInfo[] wi = new WellInfo[60000];
WellInfo[] wi2 = new WellInfo[0];
int i = 0;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:wellec.db");
//c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("select * from WELLINFO");
//c.commit();
//if(rs.getRow() > 0)
while ( rs.next() ) { //HERE IS THE PROBLEM
wi[i].wellID = rs.getInt("ID");
i++;
}
wi2 = new WellInfo[i];
for(int j = 0; j < i - 1; j++){
wi2[j] = wi[j];
}
rs.close();
stmt.close();
return wi2;
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
return wi2;
Sorry not specify the problem. Here it is:
SELECT QUERY problem when i call rs.next(), i got the error java.lang.NullPointerException.
wi[i] is null => you can't call wi[i].wellID before you instantiate wi[i], you should do something like
wi[i] = new WellInfo() then call wi[i].wellID

error in java update

if (e.getSource() == btn_updt) {
try {
String str = "img";
int max_avail;
double price;
Frame f = new Frame();
Connection con;
DriverManager
.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:dsnproj", "", "");
Statement s = con.createStatement();
// int mno=Integer.parseInt(txt_contcno.getText());
price = Double.parseDouble(txt_price.getText());
max_avail = Integer.parseInt(txt_qty_avl.getText());
String qry_up = "update category set prod_name='"
+ txt_pro_nm.getText() + "',desc='"
+ txt_pro_desc.getText() + "',photo='" + str
+ "',max_quan_avail=" + max_avail + ",cur_price="
+ price + ",per='" + ch_weight.getSelectedItem()
+ "' where p_name='" + ch_pro_nm.getSelectedItem()
+ "'";
System.out.println(qry_up);
s.execute(qry_up);
System.out.println("updated");
// JOptionPane.showMessageDialog(f,
// "Updates Successfully : ","A plain message",JOptionPane.PLAIN_MESSAGE);
} catch (Exception ae) {
System.out.println(ae.getLocalizedMessage());
}
return result;
}
and i got error as:
update category set prod_name='jjhhj',desc='jjjh',photo='img',max_quan_avail=88,cur_price=99.0,per='piece' where p_name='brush' [Microsoft][ODBC Microsoft Access Driver] Syntax error in UPDATE statement.
please help me...
Since DESC is a keyword, you must surround it with [].
Use this for your query:
String qry_up = "update category set prod_name='"
+ txt_pro_nm.getText() + "',[desc]='"
+ txt_pro_desc.getText() + "',photo='" + str
+ "',max_quan_avail=" + max_avail + ",cur_price="
+ price + ",per='" + ch_weight.getSelectedItem()
+ "' where p_name='" + ch_pro_nm.getSelectedItem()
+ "'";

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