sql Command has not properly ended - java

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 (' ....

Related

How to insert into database from netbeans

Im trying to insert a new "elev" into my table, Im struggling with the query, the variables "id" and "sovsal" are integers. How is the query supposed to look like?
try {
String nextID = db.getAutoIncrement("elev", "elev_id");
angeElevID.setText(nextID);
String id = angeElevID.getText();
String sovsal = angeSovsal.getText();
String efternamn = angeEfternamn.getText();
String fornamn = angeFornamn.getText();
db.insert("INSERT INTO ELEV values('" + id + "','" + fornamn + "','" + efternamn + "'," + sovsal + ")");
JOptionPane.showMessageDialog(null, "En ny elev har lagts till");
} catch (InfException e) {
JOptionPane.showMessageDialog(null, "nĂ¥got blev fel");
}
So the query is like
db.insert("INSERT INTO ELEV (tableElement1, tableElement2,tableElement3, tableElement4) values('"+id+"','"+fornamn+"','"+efternamn+"',"+sovsal+")");
Where the tableElements are the names in the database

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.

Parsing csv line to Java objects

I was wondering if someone here could help me, I can't find a solution for my problem and I have tried everything.
What I am trying to do is read and parse lines in a csv file into java objects and I have succeeded in doing that but after it reads all the lines it should insert the lines into the database but it only inserts the 1st line the entire time and I don't no why. When I do a print it shows that it is reading all the lines and placing them in the objects but as soon as I do the insert it wants to insert only the 1st line.
Please see my code below:
public boolean lineReader(File file){
BufferedReader br = null;
String line= "";
String splitBy = ",";
storeList = new ArrayList<StoreFile>();
try {
br = new BufferedReader(new FileReader(file));
while((line = br.readLine())!=null){
line = line.replace('|', ',');
//split on pipe ( | )
String[] array = line.split(splitBy, 14);
//Add values from csv to store object
//Add values from csv to storeF objects
StoreFile StoreF = new StoreFile();
if (array[0].equals("H") || array[0].equals("T")) {
return false;
} else {
StoreF.setRetailID(array[1].replaceAll("/", ""));
StoreF.setChain(array[2].replaceAll("/",""));
StoreF.setStoreID(array[3].replaceAll("/", ""));
StoreF.setStoreName(array[4].replaceAll("/", ""));
StoreF.setAddress1(array[5].replaceAll("/", ""));
StoreF.setAddress2(array[6].replaceAll("/", ""));
StoreF.setAddress3(array[7].replaceAll("/", ""));
StoreF.setProvince(array[8].replaceAll("/", ""));
StoreF.setAddress4(array[9].replaceAll("/", ""));
StoreF.setCountry(array[10].replaceAll("/", ""));
StoreF.setCurrency(array[11].replaceAll("/", ""));
StoreF.setAddress5(array[12].replaceAll("/", ""));
StoreF.setTelNo(array[13].replaceAll("/", ""));
//Add stores to list
storeList.add(StoreF);
}
} //print list stores in file
printStoreList(storeList);
executeStoredPro(storeList);
} catch (Exception ex) {
nmtbatchservice.NMTBatchService2.LOG.error("An exception accoured: " + ex.getMessage(), ex);
//copy to error folder
//email
}
return false;
}
public void printStoreList(List<StoreFile> storeListToPrint) {
for(int i = 0; i <storeListToPrint.size();i++){
System.out.println( storeListToPrint.get(i).getRetailID()
+ storeListToPrint.get(i).getChain()
+ storeListToPrint.get(i).getStoreID()
+ storeListToPrint.get(i).getStoreName()
+ storeListToPrint.get(i).getAddress1()
+ storeListToPrint.get(i).getAddress2()
+ storeListToPrint.get(i).getAddress3()
+ storeListToPrint.get(i).getProvince()
+ storeListToPrint.get(i).getAddress4()
+ storeListToPrint.get(i).getCountry()
+ storeListToPrint.get(i).getCurrency()
+ storeListToPrint.get(i).getAddress5()
+ storeListToPrint.get(i).getTelNo());
}
}
public void unzip(String source, String destination) {
try {
ZipFile zipFile = new ZipFile(source);
zipFile.extractAll(destination);
deleteStoreFile(source);
} catch (ZipException ex) {
nmtbatchservice.NMTBatchService2.LOG.error("Error unzipping file : " + ex.getMessage(), ex);
}
}
public void deleteStoreFile(String directory) {
try {
File file = new File(directory);
file.delete();
} catch (Exception ex) {
nmtbatchservice.NMTBatchService2.LOG.error("An exception accoured when trying to delete file " + directory + " : " + ex.getMessage(), ex);
}
}
public void executeStoredPro(List<StoreFile> storeListToInsert) {
Connection con = null;
CallableStatement st = null;
try {
String connectionURL = MSSQLConnectionURL;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
con = DriverManager.getConnection(connectionURL, MSSQLUsername, MSSQLPassword);
for(int i = 0; i <storeListToInsert.size();i++){
st = con.prepareCall( "IF EXISTS (SELECT * FROM tblPay#RetailStores WHERE StoreID = " + storeListToInsert.get(i).getStoreID() + " AND RetailID = "+ storeListToInsert.get(i).getRetailID() + ")"
+ " UPDATE tblPay#RetailStores "
+ " SET RetailID = '" + storeListToInsert.get(i).getRetailID() + "',"
+ " StoreID = '" + storeListToInsert.get(i).getStoreID() + "',"
+ " StoreName = '" + storeListToInsert.get(i).getStoreName() + "',"
+ " TestStore = 0,"
+ " Address1 = '" + storeListToInsert.get(i).getAddress1() + "',"
+ " Address2 = '" + storeListToInsert.get(i).getAddress2() + "',"
+ " Address3 = '" + storeListToInsert.get(i).getAddress3() + "',"
+ " Address4 = '" + storeListToInsert.get(i).getAddress4() + "',"
+ " Address5 = '" + storeListToInsert.get(i).getAddress5() + "',"
+ " Province = '" + storeListToInsert.get(i).getProvince() + "',"
+ " TelNo = '" + storeListToInsert.get(i).getTelNo() + "',"
+ " Enabled = 1"
+ " ELSE "
+ " INSERT INTO tblPay#RetailStores ( [RetailID], [StoreID], [StoreName], [TestStore], [Address1], [Address2], [Address3], [Address4], [Address5], [Province], [TelNo] , [Enabled] ) "
+ " VALUES "
+ "('" + storeListToInsert.get(i).getRetailID() + "',"
+ "'" + storeListToInsert.get(i).getStoreID() + "',"
+ "'" + storeListToInsert.get(i).getStoreName() + "',"
+ "0,"
+ "'" + storeListToInsert.get(i).getAddress1() + "',"
+ "'" + storeListToInsert.get(i).getAddress2() + "',"
+ "'" + storeListToInsert.get(i).getAddress3() + "',"
+ "'" + storeListToInsert.get(i).getAddress4() + "',"
+ "'" + storeListToInsert.get(i).getAddress5() + "',"
+ "'" + storeListToInsert.get(i).getProvince() + "',"
+ "'" + storeListToInsert.get(i).getTelNo() + "',"
+ "1)");
st.executeUpdate();
}
con.close();
} catch (Exception ex) {
nmtbatchservice.NMTBatchService2.LOG.error("Error executing Stored proc with error : " + ex.getMessage(), ex);
nmtbatchservice.NMTBatchService2.mailingQueue.addToQueue(new Mail("support#nmt-it.co.za", "Service Email Error", "An error occurred during Store Import failed with error : " + ex.getMessage()));
}
}
Any advise would be appreciated.
Thanks
Formatting aside, your code is wrong (I truncated the part of the query):
for(int i = 0; i <storeListToInsert.size();i++){
st = con.prepareCall( "IF EXISTS (SELECT * FROM tblPay#RetailStores ...
+ "'" + storeListToInsert.get(i).getTelNo() + "',"
+ "1)");
st.executeUpdate();
}
Don't do a classical for loop while foreach exists and can be better to use, and even if you do a classical for loop, use local variables, eg:
for(int i = 0; i <storeListToInsert.size();i++){
StoreFile item = storeListToInsert.get(i);
st = con.prepareCall( "IF EXISTS (SELECT * FROM tblPay#RetailStores ...
+ "'" + item.getTelNo() + "',"
+ "1)");
st.executeUpdate();
}
Which could translate as:
for (StoreFile item : storeListToInsert) {
st = con.prepareCall( "IF EXISTS (SELECT * FROM tblPay#RetailStores ...
+ "'" + item.getTelNo() + "',"
+ "1)");
st.executeUpdate();
}
Now, the second problem is your PreparedStatement. A PreparedStatement allow reusing, which means you don't need to create PreparedStatement per item which is what you are doing.
Also, you need to close the statement otherwise, you will exhaust resources..
You must not create it in the for loop, but before, like this:
PreparedStatement st = null;
try {
st = con.prepareCall( "IF EXISTS (SELECT * FROM tblPay#RetailStores ...
+ "SET RetailID = :RetailID ,"
+ "1)");
for (StoreFile item : storeListToInsert) {
st.setString(":RetailID", item.getRetailID());
st.executeUpdate();
}
} finally {
if (null != st) {st.close();}
}
In brief:
You need to close the PreparedStatement after usage, because it is a memory leak otherwise.
You need to rewrite your query using either named parameters, either positional parameter (like: ? or ?1 for first parameter, and so on). I favor named parameters, but they are not always available. The example I linked all use positional parameters.
You need to set the value for each parameters in the for loop, and care about the type. I expected here that getRetailID() is a String, but it might be a Long in that case that would be st.setLong.
Your query is reusable, avoiding the need to reparse it/resend it to the SQL Server. You just send the parameter's values. Beside, you can also batch update.
A PreparedStatement for a statement that you generate (like you are doing) is overkill, and beside, it is missing SQL escapement to protect the String you inject to your query to avoid it being badly interpreted (aka SQL errors) or worst, to do what it was not intended for (like, even if it is far fetched, dropping the whole database, etc).
The executeUpdate() return the number of updated rows. You can check it to see if there was updates.
You can also use Batch statement, which can help performances.
And finally, you can use opencsv to parse common CSV files.

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

Categories

Resources