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();
}
Related
When I attempt to read data from the access database there is no issue, e.g.
ResultSet equipmentData = DatabaseController.RunOperation("SELECT * FROM Equipamentos");
Code for DatabaseController:
package application;
import java.sql.*;
public class DatabaseController {
private static String databaseURL;
public static void setURL(String url) {
try {
databaseURL = "jdbc:ucanaccess://" + url + ";readonly=false";
} catch (Exception e) {
e.printStackTrace();
}
}
public static ResultSet RunOperation(String input){
ResultSet rs = null;
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection c = DriverManager.getConnection(databaseURL);
Statement st = c.createStatement();
rs = st.executeQuery(input);
}
catch(Exception e){
e.printStackTrace();
}
return rs;
}
}
However, when I try to do any operation which writes to the database it does not function. Specifically, I try to update a row with:
String operation = "UPDATE Equipamentos SET "
+ "CodigoEquipamento = '"+equipmentCode.getText()+"', "
+ "CodigoPrincipal = '"+equipType+"', "
+ "Equipamento = '"+equipmentDescription.getText()+"', "
+ "EquipamentoCritico = "+ criticalEquipment.isSelected() +", "
+ "Marca = '"+brand.getText()+"', "
+ "Tipo = '"+type.getText()+"', "
+ "NumeroSerie = '"+serialNumber.getText()+"', "
+ "OutrasCaracteristicas = '"+otherCharacteristics.getText()+"', "
+ "Observacoes = '"+observations.getText()+"' "
+ "WHERE CodigoEquipamento = '"+this.lastEquipmentCode+"'";
DatabaseController.RunOperation(operation);
which, when testing, results in the query
UPDATE Equipamentos SET CodigoEquipamento = 'R100.00', CodigoPrincipal = 'R100', Equipamento = 'Equipamento provisoriamente sem código', EquipamentoCritico = true, Marca = 'Código temporário', Tipo = 'null', NumeroSerie = 'null', OutrasCaracteristicas = 'Todas as Fichas de Trabalho feitas com este Código deverão ser enviadas de imediato para a DPA a fim de se atribuir um código', Observacoes = 'All Job Cards with this code must be sent to the DPA at once in order to attribute a new code' WHERE CodigoEquipamento = 'R100.00'
I've used this query(copy paste) in the access database, and it runs perfectly.
I have also tried deleting the row and inserting a new one with the edited values, but that also does not work.
The error that UCanAccess gives me is UCAExc:::5.0.1 General error.
Thank you for any help you can provide.
Using Erik A's suggestion I used a Prepared Statement. This did not fix my issue, however it pointed me to use .executeUpdate() instead of .executeQuery(). This fixed the error. This was because executeQuery() expected a result, as its typing is ResultSet.
Instead of creating the statement in another class I chose to create a function in the DatabaseControllerClass to handle it:
public static void saveToDatabase(String equipCode, String equipType, String equipDesc, Boolean critEquip, String brand, String type, String serialNum, String otherChar, String obs, String lastEquipCode) {
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection c = DriverManager.getConnection(databaseURL);
PreparedStatement st = c.prepareStatement("UPDATE Equipamentos SET "
+ "CodigoEquipamento = ?, "
+ "CodigoPrincipal = ?, "
+ "Equipamento = ?, "
+ "EquipamentoCritico = ?, "
+ "Marca = ?, "
+ "Tipo = ?, "
+ "NumeroSerie = ?, "
+ "OutrasCaracteristicas = ?, "
+ "Observacoes = ? "
+ "WHERE CodigoEquipamento = ?");
st.setString(1, equipCode);
st.setString(2, equipType);
st.setString(3, equipDesc);
st.setBoolean(4, critEquip);
st.setString(5, brand);
st.setString(6, type);
st.setString(7, serialNum);
st.setString(8, otherChar);
st.setString(9, obs);
st.setString(10, lastEquipCode);
st.executeUpdate();
}
catch(Exception e) {
e.printStackTrace();
}
}
Is there any issue with these lines of code? All I get is "invalid entry".
I have a database called production with a table called PRODUCTION.
try {
String mk = jTextField1.getText();
String mn = jTextField2.getText();
String ab = (String) jComboBox1.getSelectedItem();
String bc = (String) jComboBox2.getSelectedItem();
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:1527/production");
{
String host = "jdbc:mysql://localhost:1527/production";
JOptionPane.showMessageDialog(this, "connection success");
Statement stmt = con.createStatement();
String query = "update PRODUCT set FACTORY='" + ab + "' PRODUCT_NAME = '" + mk + "' UNIT= '" + bc + "' and OPENING_BALANCE'" + mn + "');";
stmt.executeUpdate(query);
JOptionPane.showMessageDialog(this, "Record has been inserted");
stmt.close();
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "invalid entry");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error in Connectivity", "Message", 2);
}
Your query is not correct :
You have to use , between the fields
You don't need to use and when you set the fields (and OPENING_BALANCE'" + mn + "')
In the end of your query there are a closed parenthesis ) that you don't need it
But your way is open to sytax error and SQL Inection you have to use PreparedStatement instead, it is more secure and more helpful :
query = "update PRODUCT set FACTORY = ?, PRODUCT_NAME = ?, UNIT= ?, OPENING_BALANCE = ?";
try (PreparedStatement update = connection.prepareStatement(query)) {
update.setString(1, ab);
update.setString(2, mk);
update.setString(3, bc);
update.setString(4, mn);
update.executeUpdate();
}
Connection con = null;
Statement stmt = null;
Statement resultStmt = null;
ResultSet rs = null;
try {
// load database driver driver
System.out.println("Database driver is: " + DataSource.getClassName());
Class.forName(DataSource.getClassName());
// connect to database from a given URL with a given username and password
System.out.println("Database URL is: " + DataSource.getURL());
con = DriverManager.getConnection(DataSource.getURL(), DataSource.getUserName(), DataSource.getPassword());
// create an SQL statement object
stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO leadcustomer " + "VALUES(1, 'junwei', 'Li', 'heaven road','test#test.com')");
String SQLStatement = "SELECT * FROM leadcustomer";
System.out.println("Q1 SQL Statement is: " + SQLStatement);
rs = resultStmt.executeQuery(SQLStatement);
while (rs.next()) {
int customerid = rs.getInt("customerid");
String fistname = rs.getString("firstname");
String surname = rs.getString("surname");
String billAddress = rs.getString("billingAddress");
String email = rs.getString("email");
System.out.println("customerid : " + customerid);
System.out.println("firstname : " + fistname);
System.out.println("surname : " + surname);
System.out.println("billingAddress : " + billAddress);
System.out.println("email : " + email);
System.out.println(customerid + " : " + fistname + "--" + surname + "--" + billAddress + ":" + email);
}
con.close();
// extract name from first row and print
} catch (SQLException e) {
// print details of SQL error
// could be multiple errors chained together
System.err.println("Error(s) occurred");
while (e != null) {
System.err.println("SQLException : " + e.getMessage());
System.err.println("SQLState : " + e.getSQLState());
System.err.println("SQLCode : " + e.getErrorCode());
e = e.getNextException();
System.err.println();
}
}
I'm trying to insert data and select the table after inserted. But it returns the error message "no results were returned by the query"
I did use executeUpdate and executeQuery for different SQL statement.
Any suggestion for that?
BTW, the insert action is running successful.
The only thing I want is just to solve out the error and execute the select statement print out the table..
Your resultStmt hasn't been initialized. Add
resultStmt = con.createStatement();
before
rs = resultStmt.executeQuery(SQLStatement);
I've come across a weird situation. The code is as below:
public static int add(String trcd, String tlcd, String dept, String doDate,
String doTime, String andConfirm, Teller admin) throws
Exception {
try {
String table1 = "table1";
String table2 = "table2";
String trap = null;
String trtype = null;
String sql = "select * from " + table2;
DataSet dataset = DBOper.DBQuery("taUtil", sql);
if (dataset.isEmpty()) {
return -1;
}
else {
HashMap map = dataset.getRow(0);
trap = (String) map.get("aut_ap_code");
trtype = (String) map.get("aut_type_code");
//point 1
sql = "insert into " + table1 + " values("+trtype + "','" + doDate + "','" + doTime + "','N','Y')";
DBOper.DBUpdate("taUtil", sql);
if (andConfirm.equals("Y")) {
//point 2
sql = "select * " + table1 +" where tr_create_date='" + doDate + "' and tr_create_time='" + doTime + "' and tr_stcd='Y'";
//point 3
DataSet dataset2 = DBOper.DBQuery("taUtil", sql);
if (dataset2.isEmpty()) {
return -2;
}
else {
String trNo = null;
HashMap map2 = dataset2.getRow(0);
trNo = (String) map2.get("tr_no");
confirm(admin, trNo, "N");
}
}
return 0;
}
}
catch (Exception e) {
throw e;
}
}
The problem is:
at point 3, it
always prints "insert" ie the previous sql value instead of the latest assignment of "select".
Does anybody knows why is it so ?
Thanks
You have a syntax error in your assignment statement:
sql = "insert into " + table1 + " values(trtype + "','" + doDate + "','" + doTime + "','N','Y')";
Try to replace it with:
sql = "insert into " + table1 + " values(" +trtype + "',' " + doDate + "','" + doTime + "','N','Y')";
I'm not sure how you even managed to compile this...
EDIT: If this syntax error does stop the code from compiling and your IDE (assuming you are using one) executes older version of the class that could not be compiled (has happened to me using Eclipse on occasions), I think it could end up doing something completely unpredictable and possibly explain this odd behavior.
I am trying to compare values from three Resultset, but there seems to exception wen I try to run it.
Could someone help me on where am going wrong. I will appreciate any help. Here's the code snippet that's throwing the error:
java.sql.Connection connDB = null;
java.lang.Object[] reconciledPaymentDetails = null;
java.util.Vector shiftsVector = new java.util.Vector(1, 1);
String status = "";
try {
Class.forName("org.postgresql.Driver");
}
catch (ClassNotFoundException ex) {
Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
}
try {
connDB = DriverManager.getConnection("jdbc:postgresql://" + hostName + ":" + portNumber
+ "/" + dbName, userName, password);
System.out.println("Connection established : [" + connDB.toString() + "]");
java.sql.Statement pstmt = connDB.createStatement();
java.sql.Statement pstmtShifts = connDB.createStatement();
java.sql.ResultSet rset = pstmt.executeQuery("SELECT DISTINCT payment_mode,
transaction_type, credit FROM ac_cash_collection WHERE shift_no = '" + shiftNumber +
"'");
while (rset.next()) {
java.sql.ResultSet rsetShifts = pstmtShifts.executeQuery("SELECT DISTINCT amount,
shift_amount FROM ac_shift_collections WHERE shift_no = '" + shiftNumber + "' AND
pay_mode ilike '"+rset.getString(1) +"'");
while (rsetShifts.next()) {
java.sql.ResultSet rset2 = pstmt.executeQuery("select debit from ac_cash_book where
shift_no='"+shiftNumber+"'");
while (rset2.next()){
double debit =rset2.getDouble("debit");
if((rset2.getDouble("debit")<=0 ))
status = "no_banked";
else if((rset2.getDouble("debit")==rsetShifts.getDouble("amount")) &&
(rsetShifts.getDouble("amount"))< rsetShifts.getDouble("shift_amount"))
status= "BntClosed";
else if (rset2.getDouble(1)==rsetShifts.getDouble("shift_amount"))
Status ="bClosed";
shiftsVector.addElement(rset.getString(1)+":"+rsetShifts.getString(1)+":"+status);
}
}
}
java.sql.ResultSet rset = pstmt.executeQuery("SELECT DISTINCT payment_mode, transaction_type, credit FROM ac_cash_collection WHERE shift_no = '" + shiftNumber + "'");
java.sql.ResultSet rset2 = pstmt.executeQuery("select debit from ac_cash_book where shift_no='"+shiftNumber+"'");
Your second call releases the resources generated by the first one, that's why the ResultSet is closed.