UCanAccess Cannot Write To Database, Although it can Read - java

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();
}
}

Related

Java [SQLITE_ERROR] SQL error or missing database (near "resi": syntax error)

i have some issues when i'm run the program. It says "[SQLITE_ERROR] SQL error or missing database (near "resi": syntax error)" and "ada yang salah:java.sql.SQLException: ResultSet is TYPE_FORWARD_ONLY". Am i passed something or what?
connection code
public void koneksiDatabase(){
try{
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:C:/Users/sqlite3/cekresi.db","root","");
System.out.println("Koneksi berhasil!");
}catch(ClassNotFoundException eclass){
System.out.println("Koneksi Gagal!");
}catch(SQLException esql){
System.out.println(esql.getMessage());
}
}
savedata code
public void simpanData(){
try {
String sql = "Insert into data resi = \"" + txtResi.getText() + "\","
+ "nama = \"" + txtNama.getText() + "\","
+ "tujuan = \"" + (String)cmbTujuan.getSelectedItem() + "\","
+ "tarif = \"" + txtTarif.getText() + "\","
+ "berat = \"" + txtBerat.getText() + "\","
+ "jumlah = \"" + txtJumlah.getText() + "\"";
Statement stmt = con.createStatement();
stmt.executeUpdate(sql);
System.out.println("berhasil!");
}catch (Exception e){
System.out.println(e);
}
tampilDataKeTabel();
}
showtable code
public void tampilDataKeTabel(){
ResultSet rs = null;
try{
Statement stmt = con.createStatement();
rs = stmt.executeQuery("select * from data");
ResultSetMetaData meta = rs.getMetaData();
int col = meta.getColumnCount();
int baris = 0;
while (rs.next()){
baris = rs.getRow();
}
dataTable = new String[baris][col];
int x = 0;
rs.beforeFirst();
while(rs.next()){
dataTable[x][0] = rs.getString("resi");
dataTable[x][1] = rs.getString("nama");
dataTable[x][2] = rs.getString("tujuan");
dataTable[x][3] = rs.getString("tarif");
dataTable[x][4] = rs.getString("berat");
dataTable[x][5] = rs.getString("jumlah");
x++;
}
tabelDisplay.setModel(new DefaultTableModel(dataTable,header));
}catch(Exception e){
System.err.println("ada yang salah:"+e);
}
}
There are syntax issues in the insert statement. The syntax should be:
INSERT INTO table (column1,column2 ,..)
VALUES( value1, value2 ,...);
So your insert statement should be something like:
String sql = "Insert into data(resi,nama,tujuan,tarif,berat,jumlah)
values(\"" + txtResi.getText() + "\","
+ \"" + txtNama.getText() + "\","
+ \"" + (String)cmbTujuan.getSelectedItem() + "\","
+ \"" + txtTarif.getText() + "\","
+ \"" + txtBerat.getText() + "\","
+ \"" + txtJumlah.getText() + "\")";
Also, there is an issue in the code to show the data.
while (rs.next()){
baris = rs.getRow();
}
This loop is traversing the result set once. So the next loop would fail as rs has already reached the end of results.
This is causing the exception : ResultSet is TYPE_FORWARD_ONLY
Instead of creating a 2D string array, Create a class corresponding to your db table and then create a List. Assuming a class named Data would be created, the second while loop would be :
List<Data> dataList = new ArrayList<>();
while(rs.next()){
Data data = new Data();
data.setResi(rs.getString("resi"));
data.setNama(rs.getString("nama"));
data.setTujuan(rs.getString("tujuan"));
data.setTarif(rs.getString("tarif"));
data.setBerat(rs.getString("berat"));
data.setJumlah(rs.getString("jumlah"));
dataList.add(data);
}

Unable to insert products into ms access db

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();
}

Java derby database not working

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();
}

send a broadcast message to all items in list in java

I would like to send a broadcast message to all numbers returned from the select statement. It saves elements in the list but then it sends the same message to everyone. What am I doing wrong? Please see my method below.
public static List<Message> listAllMessages(Connection connection) {
List<Message> msg = new ArrayList<Message>();
String messages = ReturnTexts.getMessage(connection, "EMPTYMESSAGE");
String sql = "SELECT b.`productid` as productid, p.`productname` as productname, b.`msisdn` as msisdn , MAX(b.`amount`) as amount, b.`productcode` as productcode, a.`endDate` as enddate FROM "
+ TableNames.SAVEDBIDSTABLE
+ "b LEFT JOIN "
+ TableNames.PRODUCTTABLE1
+ " p ON b.`productcode`= p.`code` "
+ " JOIN "
+ TableNames.AUCTIONTABLE1
+ " a"
+ " ON b.`productcode`= a.`productcode` "
+ "GROUP BY msisdn, productcode ";
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
if (connection == null || connection.isClosed() )
connection = DBConnection.getConnection();
// LOGGER.info(sql);
statement = DBConnection.isConnected(connection).prepareStatement(
sql);
// statement = connection.createStatement();
resultSet = statement.executeQuery();
long productid = 0;
String productname = null;
String msisdn = null;
int amount = 0;
String productcode = null;
Date enddate = null;
while (resultSet.next()) {
productid = resultSet.getLong("productid");
productname = resultSet.getString("productname");
msisdn = resultSet.getString("msisdn");
amount = resultSet.getInt("amount");
productcode = resultSet.getString("productcode");
enddate = resultSet.getTimestamp("enddate");
msg.add(new Message(Long.valueOf(productid), productname,
msisdn, amount, productcode, String.valueOf(enddate)));
}
String messages = ReturnTexts
.getMessage(connection, "BROADCAST")
.replace("XXXX", productname)
// .replace("YYYY", String.valueOf(amount))
.replace("YYYY",
String.valueOf(maxBid(productcode, connection)))
.replace("ZZZZ", String.valueOf(enddate));
//LOGGER.info(messages.toString());
try {
for (Message obj : msg) {
obj.setMessage(messages);
String apiUrl = "url/sendsms.jsp";
getResponse(apiUrl + "?" + "user="
+ URLEncoder.encode("xxx", "UTF-8")
+ "&password="
+ URLEncoder.encode("xxx", "UTF-8")
+ "&mobiles=" + obj.getMsisdn() + "&sms="
+ URLEncoder.encode(obj.getMessage(), "UTF-8"));
//bulkMessagesLog(obj.getMsisdn(), obj.getMessage(),obj.getProductcode(), connection);
bulkMessagesLog(productcode, msisdn, productname, connection);
//LOGGER.info(obj.getMsisdn() + " : " + obj.getProductcode()+ " : " + obj.getMessage());
}
} catch (UnsupportedEncodingException e) {
System.err
.println("UnsupportedEncodingException while trying to send SMS.");
e.getMessage();
}
} catch (SQLException e) {
LOGGER.error(e.getMessage());
} finally {
DBConnection.closeAllDBUsage(resultSet, statement, null);
}
return msg;
}
public static void bulkMessagesLog(String msisdn, String message,String productcode,
Connection connection) {
PreparedStatement statement = null;
String sql = "INSERT INTO " + TableNames.BULK_MESSAGESLOGTABLE
+ "(`msisdn`,`message`,`productcode`,`dateCreated`) VALUES(?,?,?,now()) ";
try {
if ( connection == null || connection.isClosed() )
connection = DBConnection.getConnection();
statement = DBConnection.isConnected(connection).prepareStatement(
sql);
statement.setString(1, msisdn);
statement.setString(2, message);
statement.setString(3, productcode);
//statement.addBatch();
statement.executeUpdate();
} catch (SQLException e) {
LOGGER.error(e.getMessage(), e);
} finally {
DBConnection.closeAllDBUsage(null, statement, connection);
}
}
You do iterate over the result set and build a list of messages in msg. Though you only create the text once, outside of the loop, so it's always the same with the (last) productname etc.
Should probably also be created in the loop.

no results were returned by the query

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);

Categories