I have a line of code to insert many variables into a database called GoodDB. for some reason I am unable to get it to work and get a syntax error.
I have read multiple threads where my code is 1:1 yet for some reason it still does not work for me
public void submitButton (ActionEvent event) throws IOException{
try {
Connection conn = DriverManager.getConnection("jdbc:sqlite:--Location--");
Statement statement = conn.createStatement();
statement.executeUpdate("INSERT INTO GooDB (Date, UID, prodCode, TableNr, TableTwo, Line, Var, Comment, CommentTwo, Person, Dept, Qty) VALUES '" + dDate.getValue() + "', '" + tfuID.getText() + "', '" +
tfprodCode.getText() + "', '" + tfTableNr.getText() + "', '" + tfLine.getText() + "', '" + tfcommentTwo.getText() + "', '" + taComm.getText() + "', '" + cbPerson.getValue() + "', '" + cbTableTwo.getValue() + "', '" +
cbDept.getValue() + "', '" + cbQty.getValue() + "'");
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("u good");
alert.setHeaderText("u good");
alert.setContentText(null);
alert.showAndWait();
} catch (SQLException e){
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("DB Error");
alert.setHeaderText("DB Connection Failed");
alert.setContentText(e.getMessage());
alert.showAndWait();
}
}
Upon entering data I get Error message described in "catch" showing
[SQLITE_ERROR] SQL error or missing database (near "'null'": syntax error)
Related
I am trying to insert data from my netbeans to mysql workbench. there is no problem with the query but when I run the program a message box appear "Unknown column 'empJob' in 'field list '" . What seems to be the problem?
and just to Know i tried this on another table and it works just fine! but in this one it doesn't work!
int id, Salary;
String name, Address, Jop;
id = Integer.parseInt(tNo.getText());
name = tName.getText();
Address = tAddress.getText();
Jop = tJop.getText();
Salary = Integer.parseInt(tNo.getText());
String sql = "insert into employee(empid,empName, empAddress,empJob,empSalary) values('" + id + "','" + name + "' , '" + Address + "','" + Jop + "','" + Salary + "')";
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
int x = st.executeUpdate(sql);
if (x > 0) {
JOptionPane.showMessageDialog(prev, x + "rows effected");
} else {
JOptionPane.showMessageDialog(prev, "insert failed");
}
Do you have a typo? You write empJob -> but your variable is called Jop. So maybe it should be empJop.
String sql = "insert into employee(empid,empName, empAddress,empJop,empSalary) values('" + id + "','" + name + "' , '" + Address + "','" + Jop + "','" + Salary + "')";
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.
i'm trying to update paradox table from java but i'm getting an Exception
java.sql.SQLException: [Microsoft][ODBC Paradox Driver] Operation must use an updateable query.
java.sql.SQLException: [Microsoft][ODBC Paradox Driver] Operation must use an updateable query.
java.sql.SQLException: [Microsoft][ODBC Paradox Driver] Operation must use an updateable query.
I'm using this code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Connection paradoxCon = paradox.createConnection();
Results res = new Results();
res.getAll();
if (res.allRes.isEmpty()) {
JOptionPane.showMessageDialog(mainPanel, "There are no Finished or Postponed Games!", "Error", JOptionPane.ERROR_MESSAGE);
} else {
int y = res.allRes.size();
for (int x = 0; x < y; x = x + 1) {
try {
if (res.getAll().get(x).Reversed == 0) {
if (res.getAll().get(x).Status.equals("Fin")) {
String sql = "UPDATE Kvote SET _45_d = '" + res.getAll().get(x).HThome + "', _45_g = '" + res.getAll().get(x).HTaway + "', _90_d= '" + res.getAll().get(x).FThome + "', _90_g = '" + res.getAll().get(x).FTaway + "', Ok='Y' WHERE Kolo = '" + res.getAll().get(x).tRound + "' AND Sifra='" + res.getAll().get(x).TID + "'";
PreparedStatement ps = paradoxCon.prepareStatement(sql);
ps.executeUpdate();
}
if (res.getAll().get(x).Status.equals("Post")) {
String sql = "UPDATE Kvote SET _45_d = '" + res.getAll().get(x).HThome + "', _45_g = '" + res.getAll().get(x).HTaway + "', _90_d= '" + res.getAll().get(x).FThome + "', _90_g = '" + res.getAll().get(x).FTaway + "', Ok='O' WHERE Kolo = '" + res.getAll().get(x).tRound + "' AND Sifra='" + res.getAll().get(x).TID + "'";
PreparedStatement ps = paradoxCon.prepareStatement(sql);
ps.executeUpdate();
}
}
if (res.getAll().get(x).Reversed == 1) {
if (res.getAll().get(x).Status.equals("Fin")) {
String sql = "UPDATE Kvote SET _45_d = '" + res.getAll().get(x).HTaway + "', _45_g = '" + res.getAll().get(x).HThome + "', _90_d= '" + res.getAll().get(x).FTaway + "', _90_g = '" + res.getAll().get(x).FThome + "', Ok='Y' WHERE Kolo = '" + res.getAll().get(x).tRound + "' AND Sifra='" + res.getAll().get(x).TID + "'";
PreparedStatement ps = paradoxCon.prepareStatement(sql);
ps.executeUpdate();
}
if (res.getAll().get(x).Status.equals("Post")) {
String sql = "UPDATE Kvote SET _45_d = '" + res.getAll().get(x).HTaway + "', _45_g = '" + res.getAll().get(x).HThome + "', _90_d= '" + res.getAll().get(x).FTaway + "', _90_g = '" + res.getAll().get(x).FThome + "', Ok='O' WHERE Kolo = '" + res.getAll().get(x).tRound + "' AND Sifra='" + res.getAll().get(x).TID + "'";
PreparedStatement ps = paradoxCon.prepareStatement(sql);
ps.executeUpdate();
}
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
res.getAll().clear();
} catch (ParseException ex) {
Logger.getLogger(AutoResultsImporterView.class.getName()).log(Level.SEVERE, null, ex);
}
}
I Solve the problem using INTERSOLV 3.11 32-BIT ParadoxFile (*.db) driver
I created an System DSN Data Source Using this driver and connect to this Data Source
I have create an android application where in users can add, update, and delete stuffs from the database
In my DataSource java file i have this code:
public void addWebsite(String sitename, String username, String password) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_URL, sitename);
values.put(MySQLiteHelper.COLUMN_USERNAME, username);
values.put(MySQLiteHelper.COLUMN_PASSWORD, password);
database.insert(MySQLiteHelper.TABLE_URL, null,values);
}
the above code makes the insert statement.
public void updateWebsite(WebsiteRecords website){
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_URL, website.getSitename());
values.put(MySQLiteHelper.COLUMN_USERNAME, website.getUsername());
values.put(MySQLiteHelper.COLUMN_PASSWORD, website.getPassword());
database.update(MySQLiteHelper.TABLE_URL, values, MySQLiteHelper.COLUMN_ID + " = " + website.getId(), null);
}
the above code displays an update statement
public void deleteWebsite(WebsiteRecords website) {
database.delete(MySQLiteHelper.TABLE_URL, MySQLiteHelper.COLUMN_ID + " = " + website.getId(), null);
}
and lastly, the above code is for the delete statement.
My problem is, I get this username from my login, and from that I want to add, update and delete stuffs which has the username i got from my login screen. I was thinking of making
Cursor mCursor = database.rawQuery("INSERT INTO " + TABLE_URL + " VALUES('" + sitename + "', '" + username + "', '" + password + "') " WHERE loginname=?", new String [] {loginname});
or anything like that but I am scared that it won't work. Same goes with the update and delete. It will only add, update, delete, view files which has a loginname of for instance "iamcoolin3d".
Anyone can help me with this?
The line:
Cursor mCursor = database.rawQuery("INSERT INTO " + TABLE_URL + " VALUES('" + sitename + "', '" + username + "', '" + password + "') " WHERE loginname=?", new String [] {loginname});
Should be:
Cursor mCursor = database.rawQuery("INSERT INTO " + TABLE_URL + " VALUES('" + sitename + "', '" + username + "', '" + password + "') WHERE loginname=?", new String [] {loginname});
there is an extra " before WHERE
There is a problem with your last line, you must put WHERE in the String, otherwise it won't work.
I am trying to insert data into a database and once again I cant seem to get to the bottom as to why I am getting a general error.
Any advice as to how to overcome this problem.
Class.forName(driverName);
connection = DriverManager.getConnection(SourceURL, user, password);
int rowAdded;
Object typeId = comboKeys.getSelectedItem();
String typeIdString = typeId.toString();
int typeIdInt = Integer.parseInt(typeIdString);
String animalIDString = txtAnimalID.getText();
int animalID = Integer.parseInt(animalIDString);
System.out.println(animalID);
String name = txtName.getText();
Statement statement = connection.createStatement();
String queryString = "INSERT INTO Animal (animalID, name, typeIDForeign) VALUES (" + animalID + ", '" + name + "', '" + typeIdInt + "')";
rowAdded = statement.executeUpdate(queryString);
connection.close();
Kind regards
Arian
Error
You have typeIdInt as Integer, however in the sql query, you are stating it as string (because you surround it with single quotes)
Solution
String queryString = "INSERT INTO Animal (animalID, name, typeIDForeign) VALUES (" + animalID + ", '" + name + "', '" + typeIdInt + "')";
should be :
String queryString = "INSERT INTO Animal (animalID, name, typeIDForeign) VALUES (" + animalID + ", '" + name + "', " + typeIdInt + ")";
Look at " + typeIdInt + ". You have '" + typeIdInt + "'
Good Luck!!!