How to insert into database from netbeans - java

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

Related

inserting to database using java gui

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 + "')";

no such column: hey (code 1 SQLITE_ERROR[1]): , while compiling: SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = hey

Log Cat:
no such column: hey (code 1 SQLITE_ERROR[1]): , while compiling: SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = hey
code:
102) public String getID(String note){
103) SQLiteDatabase db = this.getWritableDatabase();
104) String query = ("SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = " + note);
105) db.rawQuery(query,null);
106) return query;
107) }
I do have a column name hey in my Database
Database Picture
Your terminology is confused.
hey is a value, NOTEMEMOS is a column.
You need to quote the value hey to let the SQL compiler know that it is a string value, rather than a column you are trying to compare against.
String query = ("SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = '" + note + "'");
Just a note, you would be better off using a parameterised query, as using raw values is insecure (see SQL injection).
String query = ("SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = ?"); // That's right, quotes aren't needed for a parameterized query.
String result = "";
Cursor cursor = db.rawQuery(query,new String[] {note} );
if (cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(COL_0));
}
cursor.close();
return result;
Your query should look like this
SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = 'hey'
Let me know if it helps
The way that you concatenate the parameter note creates this sql statement:
SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = hey
so hey is considered a column identifier and not a string literal because it is not enclosed inside single quotes.
You could do this instead:
String query = "SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = '" + note + "'";
and it would work.
But the recommended way is passing parameters as a string array like this:
String query = "SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = ?";
Cursor cursor = db.rawQuery(query, new String[] {note});
return cursor;
This way you don't worry about single quotes as this is taken care of by rawQuery().
I guess you want to return the Cursor object and not the sql query string, right?

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

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.

MySQLSyntaxErrorException: Unknown column ' ____ ' in 'field list'

I get the following MySQL exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'book.call_Number' in 'field list'.
What does that mean and how can I solve it?
Here is the code responsible for this exception:
public void actionPerformed(ActionEvent e) {
list.clearSelection();
String selectString = " ";
String afName = auth_fName.getText();
String aMI = auth_MI.getText();
String alName = auth_lName.getText();
String tField = titleField.getText();
String sField = subjectField.getText();
try {
Connection conn = Database.getConnection();
Statement s = conn.createStatement();
if (!afName.equals("") && (!aMI.equals("")) && (!alName.equals("")) && (!tField.equals("")) && (!sField.equals(""))) {
selectString = "SELECT a.call_Number as callNbr "
+ "FROM book a "
+ "FULL JOIN transaction b "
+ "ON a.call_Number=b.call_Number";
}
s = conn.createStatement();
System.out.println(selectString);
ResultSet rs = s.executeQuery(selectString);
while (rs.next()) {
String call_Num = rs.getString("call_Number");
String title = rs.getString("title");
String auth_lName = rs.getString("auth_lName");
String auth_MI = rs.getString ("auth_MI");
String auth_fName = rs.getString("auth_fName");
String availability = rs.getString("availability");
view = new View(call_Num, title, auth_lName, auth_MI, auth_fName, availability);
vList.add(view);
System.out.println(view);
}
rs.close();
s.close();
conn.close();
list.setListData(vList.toArray());
} catch (Exception ex) {
ex.printStackTrace();
}
}
Here is the DDL and content:
s.executeUpdate (
"CREATE TABLE book ("
+ "call_Number CHAR(10),"
+ "PRIMARY KEY (call_Number),"
+ "auth_fName CHAR(30)NOT NULL, auth_MI CHAR(2),"
+ "auth_lName CHAR(50)NOT NULL, title CHAR(100) NOT NULL,"
+ "subject CHAR(30) NOT NULL)");
count = s.executeUpdate (
"INSERT INTO book"
+ " VALUES"
+ "('MY.111.000', 'Mark', 'M','Bradshaw','Mystery Under the Sun','mystery'),"
+ "('MY.111.001', 'Mark','','Twain','The Adventures of Huckleberry Finn','mystery'),"
+ "('SF.111.002', 'Kito', 'M','Bradford','Mr. Roboto','science fiction'),"
+ "('SF.111.003', 'Eric','','Laslow','Science Fiction - Can It Happen?','science fiction'),"
+ "('AV.111.004', 'Rashad','','Cheeks','Fire Under the Bridge','adventure'),"
+ "('AV.111.005', 'Samantha','A','Appleby','The Open Sea','adventure'),"
+ "('CO.111.006', 'Lindsey', '','Butterby','What? We cant spend anymore!?','comedy'),"
+ "('CO.111.007', 'Judy', 'S','Yates','So this is life?','comedy'),"
+ "('IN.111.008', 'Elizabeth', 'J','Lee','Mystery Under the Sun','international'),"
+ "('IN.111.009', 'Gabriella', 'M','Rodriguez','Love in Brazil','international')");
*******t_action table***************************
//create transaction table
s.executeUpdate (
"CREATE TABLE t_action ("
+ "patron_ID CHAR(10) NOT NULL,"
+ "call_Number CHAR(10) NOT NULL, check_Out_Date DATE NOT NULL, check_In_Date DATE NOT NULL,"
+ "PRIMARY KEY (patron_ID, call_Number),"
+ "avail CHAR(15), total_Charge FLOAT)");
count3 = s.executeUpdate (
"INSERT INTO t_action"
+ " VALUES"
+ "('P222200000','MY.111.000','2011-03-08','2011-03-15','AVAILABLE',5.00),"
+ "('P222200001','MY.111.001','2011-03-31','2011-04-6','DUE 2011-04-6',5.00),"
+ "('P222200002','SF.111.002','2011-03-30','2011-04-5','DUE 2011-04-5',5.00),"
+ "('P222200003','SF.111.003','2011-03-29','2011-04-4','DUE 2011-04-4',5.00),"
+ "('P222200004','AV.111.004','2011-03-28','2011-04-3','DUE 2011-04-3',5.00),"
+ "('P222200005','AV.111.005','2011-03-27','2011-04-2','DUE 2011-04-2',5.00),"
+ "('P222200006','CO.111.006','2011-03-26','2011-04-1','DUE 2011-04-1',5.00),"
+ "('P222200007','CO.111.007','2011-01-06','2011-01-12','AVAILABLE',5.00),"
+ "('P222200008','IN.111.008','2011-02-06','2011-02-12','AVAILABLE',5.00),"
+ "('P222200009','IN.111.009','2011-03-06','2011-03-12','AVAILABLE',5.00)");
Use a <column> as predicate like below:-
selectString = "SELECT a.call_Number as callNbr, ... "
+ "FROM book a"
+ "FULL JOIN transaction b"
+ "ON a.call_Number=b.call_Number";
And then change the code to look for callNbr :-
String call_Num = rs.getString("callNbr");
HTH.
Change your query to this:
selectString = "SELECT a.call_Number "
+ "FROM book a "
+ "INNER JOIN transaction b "
+ "ON a.call_Number=b.call_Number";
MySQL does not support FULL OUTER JOIN. If you really need the effect of that - you'll need 2 selects with a UNION. Although from looks of it - does not seem like that would be necessary.

Categories

Resources