Im receiving a number of different errors when trying to insert products into my access DB. Such as Malformed String: ). User lacks privilege or object cant be found. Different errors when i try and insert different products.
tried re creating the db, debugging to the hilt.
public boolean addNewProduct(Product product)
{
String Make = "";
String Model = "";
String Type = "";
String Genre = "";
String AttConsole = "";
String Desc = "";
if(product.getClass().getName().equals("Models.Game"))
{
Game game = (Game)product;
Genre = String.valueOf(game.getGenre());
AttConsole = String.valueOf(game.getAttributedConsole());
Desc = String.valueOf(game.getDescription());
}
else if(product.getClass().getName().equals("Models.Console"))
{
Console console = (Console)product;
Make = String.valueOf(console.getMake());
Model = String.valueOf(console.getModel());
Desc = String.valueOf(console.getDescription());
}
else
{
Peripheral peripheral = (Peripheral)product;
Type = String.valueOf(peripheral.getType());
Desc = String.valueOf(peripheral.getDescription());
}
try
{
Class.forName(driver);
Connection conn = DriverManager.getConnection(connectionString);
Statement stmt = conn.createStatement();
stmt.executeUpdate("INSERT INTO Products (ProductName, Price, StockLevel, Description, Genre, AttributedConsole, Make, Model, Type) VALUES "
+ "('" + product.getProductName() + "','" + product.getPrice() + "','" + product.getStocklevel()
+ "','" + Desc + "','" + Genre + "','" + AttConsole +
"','" + Make + "','" + Model + "'," + Type + ")");
//sql statement to add new products to database
conn.close();
return true;
}
catch(Exception ex)
{
String message = ex.getMessage();
return false;
}
}
ex = (net.ucanaccess.jdbc.UcanaccessSQLException) net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::4.0.4 unexpected token: )
ex = (net.ucanaccess.jdbc.UcanaccessSQLException) net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::4.0.4 user lacks privilege or object not found: RAZOR
Don't use string concatenation to insert column values into SQL command text. Search for "SQL Injection" or "Little Bobby Tables" for more information on why that is a "Bad Thing"™.
Instead, use a PreparedStatement to run a parameterized query, e.g.,
String sql = "INSERT INTO tableName (intColumn, textColumn) VALUES (?, ?)";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, 12345);
ps.setString(2, "my text value");
ps.executeUpdate();
}
I want to get my ItemName columns value to one String separate from commas.
I tried like this.but its not working
String sql = "SELECT `ItemName` FROM `invoicelist` WHERE `InvoiceId` = '"+invoicenum+"' ";
try {
ResultSet rs = CODE.DbAccess.getdata(sql);
while (rs.next()) {
String em = rs.getString("ItemName");
description = em.replace("\n", ",");
System.out.println(description);
}
You should change to this, if you want to do the concatenation in java:
String sql = "SELECT `ItemName` FROM `invoicelist` WHERE `InvoiceId` = '" + invoicenum + "' ";
try {
ResultSet rs = CODE.DbAccess.getdata(sql);
while (rs.next()) {
description += rs.getString("ItemName") + ",";
}
description = description.substring(0, description.length() - 1);
//System.out.println(description);
}
If you want to concatenate in query then you could search for GROUP_CONCAT() function
String sql = "SELECT `ItemName` FROM `invoicelist` WHERE `InvoiceId` = '" + invoicenum + "' ";
try {
ResultSet rs = CODE.DbAccess.getdata(sql);
StringBuilder builder = new StringBuilder(); // used to store string and append data further if you want
while (rs.next()) {
builder.append(rs.getString("ItemName").append(","); // adding data/Item name to builder and appending comma after adding item name
}
if(builder.length() > 0){ // if there's some data inside builder
builder.setLength(builder.length() - 1); // remove last appended comma from builder
}
System.out.println("Command Separated Data" + builder.toString()); // final data of item name
}
Other way is to concate result from SQL itself.(here's a MySQL compatible code)
String sql = "SELECT group_concat(`ItemName`) as items FROM `invoicelist` WHERE `InvoiceId` = '" + invoicenum + "' ";
try {
ResultSet rs = CODE.DbAccess.getdata(sql);
String data = "";
while (rs.next()) {
data = rs.getString("items")
}
System.out.println("Command Separated Data" + data);
}
Here is sample code ...
Statement stmt = con.createStatement();
String query = "select * from work_product where product_name ='" + ch + "' ";
System.out.println(query); // displaying only `
ResultSet rs = stmt.executeQuery(query);
System.out.println(query);
while (rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
If String passed Instead of passing variable then it works ...like
ResultSet rs = stmt.executeQuery("select * from work_product where product_name ='product' ");
I also used preparedStatement...but not working ...
PreparedStatement statement = con.prepareStatement("select * from work_thing_db.work_product where product_name = ? ");
statement.setString(1,ch);
Here is full code ....
#FXML protected void keyReleased(KeyEvent evt)throws Exception {
//SetTimer();
if (evt.getCode() != KeyCode.BACK_SPACE) {
String ch = evt.getText();
//runThread();
concateString = concateString + ch; //concateString has scope
if (evt.getCode() == KeyCode.ENTER) {
System.out.println("Enter Key Fired ");
System.out.println(concateString);
dbSearch(concateString);
}
}
}
private void dbSearch(String ch){
System.out.println("In dbSearch");
System.out.println("Concate String :"+ch);
String query = "select * from work_product where product_name ='" + ch + "' ";
System.out.println("Query is :"+query);
dbConnector conn = new dbConnector();
Connection con = conn.dbConnection();
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()){
System.out.println(rs.getString(1)+" "+rs.getString(2));
}
}catch(Exception e){System.out.println(e);}
}
Using : IntelliJ IDEA 14 CEOutput :
Enter key Fired
product
In dbSearch
Concat String :product
'
kindly point out my mistake ... i'm new in java... and further i need to use like and or with it .... please provide answer with explanation... Thanks in advance.
It's possible there is no match in the data. You could run a non filtered query first and see what values you have for product_name in the table.
I haven't thought of it....
private void dbSearch(String ch){
System.out.println("In dbSearch");
System.out.println("Concate String :"+ch);
ch = ch.trim().toString(); // trim and type cast ... its working
String query = "select * from work_product where product_name ='" + ch + "' ";
System.out.println("Query is :"+query);
dbConnector conn = new dbConnector();
Connection con = conn.dbConnection();
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()){
System.out.println(rs.getString(1)+" "+rs.getString(2));
}
}catch(Exception e){System.out.println(e);}
}
Now it is fetching data properly ...
There is something wrong in the way you concatenate the string
if (evt.getCode() != KeyCode.BACK_SPACE) {
String ch = evt.getText();
//runThread();
concateString = concateString + ch; //concateString has scope
if (evt.getCode() == KeyCode.ENTER) {
System.out.println("Enter Key Fired ");
System.out.println(concateString);
dbSearch(concateString);
}
}
so when the user will enter "ENTER" (can be \n or \r) you will concatenate before the condition of the key value so concateString will always contain your string + "ENTER" (i.e. the carriage return). Thats the reason you only get the quote when you print your query
Not to modify much of your code, you can do
if (evt.getCode() != KeyCode.BACK_SPACE) {
String ch = evt.getText();
//runThread();
if (evt.getCode() == KeyCode.ENTER) {
System.out.println("Enter Key Fired ");
System.out.println(concateString);
dbSearch(concateString);
} else {
concateString = concateString + ch; //concateString has scope
}
}
and so you will pass the correct string
I want this function to display the highest value and the index in the array.If the index is the highest, it will retrieve all the value in sql. But when I run this program, it displays a lot of values...How to solve it?
private void pick_highest_value_here_and_display(ArrayList<Double> value) throws Exception {
// TODO Auto-generated method stub
double aa[]=value.stream().mapToDouble(v -> v.doubleValue()).toArray();
double highest=aa[0];
System.out.println(highest); // display value in aa[0]
for(int i=1;i<aa.length;i++)
{
if(aa[i]>highest)
{
highest=aa[i];
System.out.println(highest); //print the highest value only
System.out.println(i);
String sql ="Select * from placeseen where ID =?";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDouble(1, i+1);
ResultSet rs = ps.executeQuery();
if (rs.next())
{
String aaa=rs.getString("place1");
String bbb=rs.getString("place2");
String cc=rs.getString("place3");
String dd=rs.getString("place4");
String ee=rs.getString("place5");
String ff=rs.getString("place6");
String gg=rs.getString("place7");
String hh=rs.getString("place8");
String iii=rs.getString("place9");
String jj=rs.getString("place10");
String kk=rs.getString("place11");
String ll=rs.getString("place12");
String mm=rs.getString("place13");
String nn=rs.getString("place14");
String oo=rs.getString("place15");
String pp=rs.getString("budget");
Tourism to =new Tourism();
to.setPlace1(aaa);
to.setPlace2(bbb);
to.setPlace3(cc);
to.setPlace4(dd);
to.setPlace5(ee);
to.setPlace6(ff);
to.setPlace7(gg);
to.setPlace8(hh);
to.setPlace9(iii);
to.setPlace10(jj);
to.setPlace11(kk);
to.setPlace12(ll);
to.setPlace13(mm);
to.setPlace14(nn);
to.setPlace15(oo);
to.setBudget(pp);
DispDay dc=new DispDay();
dc.setVisible(true);
}
ps.close();
rs.close();
conn.close();
}
else if(highest==aa[0])
{
String sql ="Select * from placeseen where ID =1";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs.next())
{
String aaa=rs.getString("place1");
String bbb=rs.getString("place2");
String cc=rs.getString("place3");
String dd=rs.getString("place4");
String ee=rs.getString("place5");
String ff=rs.getString("place6");
String gg=rs.getString("place7");
String hh=rs.getString("place8");
String iii=rs.getString("place9");
String jj=rs.getString("place10");
String kk=rs.getString("place11");
String ll=rs.getString("place12");
String mm=rs.getString("place13");
String nn=rs.getString("place14");
String oo=rs.getString("place15");
String pp=rs.getString("budget");
Tourism to =new Tourism();
to.setPlace1(aaa);
to.setPlace2(bbb);
to.setPlace3(cc);
to.setPlace4(dd);
to.setPlace5(ee);
to.setPlace6(ff);
to.setPlace7(gg);
to.setPlace8(hh);
to.setPlace9(iii);
to.setPlace10(jj);
to.setPlace11(kk);
to.setPlace12(ll);
to.setPlace13(mm);
to.setPlace14(nn);
to.setPlace15(oo);
to.setBudget(pp);
DispDay dc=new DispDay();
dc.setVisible(true);
}
ps.close();
rs.close();
conn.close();
}
}
Use MAX
Please change your approach, and use the SQL MAX function. Something like,
String sql = "SELECT * FROM placeseen WHERE budget = ("
+ "SELECT MAX(budget) FROM placeseen)";
You could then use something like
int id = rs.getInt("id");
float budget = rs.getFloat("budget");
And I would recommend limiting the columns (if you only want the two) like
String sql = "SELECT id, budget FROM placeseen WHERE budget = ("
+ "SELECT MAX(budget) FROM placeseen)";
Why not use a for (int i = 0; i < array.lenght; i++)?
Store array[i] in a variable, and the actual int found in that index in another variable. Then, when you loop through it more: if (array[i] > biggestInt), store the new index number and new biggest integer in their appropriate variables.
I am trying to update a table in the database where i m accepting fees from the students and maintaining the record of the amount received, total amount received, and the mode of payment etc.
my code is as follows:
private void pay_saveActionPerformed(java.awt.event.ActionEvent evt) {
String dbUrl = "jdbc:mysql://localhost/hostel";
String dbClass = "com.mysql.jdbc.Driver";
PreparedStatement ps1 = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection (dbUrl,"root","17121990");
System.out.println("connected!");
String firstname=pay_enter_firstname.getText();
String lastname=pay_enter_lastname.getText();
String amt=pay_enter_amt.getText();
int amount=Integer.parseInt(amt);
String day=pay_enter_date.getText();
String cheque_no=pay_enter_chequeno.getText();
String mode=pay_enter_mode.getText();
int totalamount=10000;
int bal_amt=totalamount-amount;
String remark=pay_enter_remark.getText();
int id = Integer.parseInt(pay_enter_id.getText());
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment");
if(rs.next())
{
stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment");
while(rs.next())
{
int temp =rs.getInt(1);
if (temp ==id)
{
int amtrecvd2= rs.getInt(2);
bal_amt=totalamount- (amtrecvd2+amount);
String updt = "UPDATE payment SET Amountreceivd="+(amtrecvd2+amount)+",lastamtreceived="+amount+",dte='"+day+"', balance_amt ="+bal_amt+" WHERE id ="+temp+";" ;
Statement stmt1 = con.createStatement();
int result = stmt1.executeUpdate(updt);
}
}
}
if(!rs.next())
{
String str=" INSERT INTO payment(id, firstname,lastname,Amountreceivd,dte,lastamtreceived,Creditcashcheque,"
+ "cheque_no,balance_amt,totalamount,Remark) VALUES ("+id+",'"+firstname+"','"+lastname+"',"+amount+",'"+day+"',"+amount+",'"+mode+"','"+cheque_no+"',"+ bal_amt+","+totalamount+",'"+remark+"')";
Statement stmt1=con.createStatement();
int result=stmt1.executeUpdate(str);
panel_feesframe.setVisible(false);
}
panel_feesframe.setVisible(false);
con.close();
}
catch (ClassNotFoundException | SQLException | NumberFormatException e)
{
e.printStackTrace();
}
}
Initially when i add new values i get it properly but when i am trying to update an existing row i get the error that i m making a duplicate entry for primary key id.
what condition should i check so that i come to know that the result set is not having that particular id value and new person is paying the fee??
This condition:
if(!rs.next())
is being checked outside the while loop. This condition is always true and will try to insert a record even if update has taken place.
To avoid this, i suggest using a flag variable. Once an update has occurred, set the value of this flag to 1.
Check if it has been made 1 instead of if(!rs.next()) and go inside.
You're two if statements are colliding...
// If this is true...
if(rs.next()) {
// ...
// Looping till the it's false...
while(rs.next()) {
// ....
}
}
// Will mean that this is false...
if(!rs.next())
You should be using an else
if(rs.next()) {
// ...
while(rs.next()) {
// ....
}
} else {...}
Updated
After an enlightening conversion with Aashray (thanks), we've concluded that your logic is broken
Rather then manually trying to find the record manually by match the id's let the SQL database do it for you.
Instead of....
ResultSet rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment");
You should be using...
ResultSet rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment where id = " + id);
This will return a ResultSet that is either empty (no matches) or with (hopefully) one row.
From there, calling rs.next() will now let you branch of between an update or insert correctly.
private void pay_saveActionPerformed(java.awt.event.ActionEvent evt) {
String dbUrl = "jdbc:mysql://localhost/hostel";
String dbClass = "com.mysql.jdbc.Driver";
PreparedStatement ps1 = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(dbUrl, "root", "17121990");
System.out.println("connected!");
String firstname = pay_enter_firstname.getText();
String lastname = pay_enter_lastname.getText();
String amt = pay_enter_amt.getText();
int amount = Integer.parseInt(amt);
String day = pay_enter_date.getText();
String cheque_no = pay_enter_chequeno.getText();
String mode = pay_enter_mode.getText();
int totalamount = 10000;
int bal_amt = totalamount - amount;
String remark = pay_enter_remark.getText();
int id = Integer.parseInt(pay_enter_id.getText());
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment where id = " + id);
if (rs.next()) {
int amtrecvd2 = rs.getInt(2);
bal_amt = totalamount - (amtrecvd2 + amount);
String updt = "UPDATE payment SET Amountreceivd=" + (amtrecvd2 + amount) + ",lastamtreceived=" + amount + ",dte='" + day + "', balance_amt =" + bal_amt + " WHERE id =" + id + ";";
Statement stmt1 = con.createStatement();
int result = stmt1.executeUpdate(updt);
} else {
String str = " INSERT INTO payment(id, firstname,lastname,Amountreceivd,dte,lastamtreceived,Creditcashcheque,"
+ "cheque_no,balance_amt,totalamount,Remark) VALUES (" + id + ",'" + firstname + "','" + lastname + "'," + amount + ",'" + day + "'," + amount + ",'" + mode + "','" + cheque_no + "'," + bal_amt + "," + totalamount + ",'" + remark + "')";
Statement stmt1 = con.createStatement();
int result = stmt1.executeUpdate(str);
panel_feesframe.setVisible(false);
}
panel_feesframe.setVisible(false);
con.close();
} catch (ClassNotFoundException | SQLException | NumberFormatException e) {
e.printStackTrace();
}
}
I think this may help you
private void pay_saveActionPerformed(java.awt.event.ActionEvent evt) {
String dbUrl = "jdbc:mysql://localhost/hostel";
String dbClass = "com.mysql.jdbc.Driver";
PreparedStatement ps1 = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection (dbUrl,"root","17121990");
System.out.println("connected!");
String firstname=pay_enter_firstname.getText();
String lastname=pay_enter_lastname.getText();
String amt=pay_enter_amt.getText();
int amount=Integer.parseInt(amt);
String day=pay_enter_date.getText();
String cheque_no=pay_enter_chequeno.getText();
String mode=pay_enter_mode.getText();
int totalamount=10000;
int bal_amt=totalamount-amount;
String remark=pay_enter_remark.getText();
int id = Integer.parseInt(pay_enter_id.getText());
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment");
if(rs.next())
{
stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment");
while(rs.next())
{
int temp =rs.getInt(1);
if (temp ==id)
{
int amtrecvd2= rs.getInt(2);
bal_amt=totalamount- (amtrecvd2+amount);
String updt = "UPDATE payment SET Amountreceivd="+(amtrecvd2+amount)+",lastamtreceived="+amount+",dte='"+day+"', balance_amt ="+bal_amt+" WHERE id ="+temp+";" ;
Statement stmt1 = con.createStatement();
int result = stmt1.executeUpdate(updt);
}
}
}
else
{
String str=" INSERT INTO payment(id, firstname,lastname,Amountreceivd,dte,lastamtreceived,Creditcashcheque,"
+ "cheque_no,balance_amt,totalamount,Remark) VALUES ("+id+",'"+firstname+"','"+lastname+"',"+amount+",'"+day+"',"+amount+",'"+mode+"','"+cheque_no+"',"+ bal_amt+","+totalamount+",'"+remark+"')";
Statement stmt1=con.createStatement();
int result=stmt1.executeUpdate(str);
panel_feesframe.setVisible(false);
}
panel_feesframe.setVisible(false);
con.close();
}
catch (ClassNotFoundException | SQLException | NumberFormatException e)
{
e.printStackTrace();
}