Java derby database not working - java

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

Related

UCanAccess Cannot Write To Database, Although it can Read

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

Java sqlite row disappear after Select query

I have a sqlite db file created by other program, and checked everything is fine.
Then after doing select query to get some data, some of the row disappear after this process. I tried to use prepareStatement and though it worked but this remained.
my code
private ForecastTableItem selectItemPrepareStatement(String tableName, String columnName, String name) {
ForecastTableItem item = null;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:" + dbLocation);
System.out.println("Selecting item from tableName: "+tableName + " of col: "+columnName + " : "+name);
String query = "SELECT * FROM " + tableName + " WHERE " + columnName + "=? COLLATE NOCASE";
pstmt = conn.prepareStatement(query);
pstmt.setString(1, name);
rs = pstmt.executeQuery();
if (rs.next()) {
if (tableName.equalsIgnoreCase("mainTable")) {
item = new ForecastTableItem();
item.setId(rs.getInt("Id"));
item.setTitle(rs.getString("title"));
item.setLink(rs.getString("link").toLowerCase());
item.setPositionType(rs.getString("positionType"));
item.setPackageName(rs.getString("packageName"));
item.setCsvFilePath(rs.getString("csvFilePath"));
item.setSubpackageName(rs.getString("subpackageName"));
item.setTimeFrame(rs.getString("timeFrame"));
item.setForecastDate(rs.getString("forecastDate"));
item.setTargetDate(rs.getString("targetDate"));
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally{
if(pstmt != null) try{ pstmt.close();} catch(SQLException e){};
if(rs != null) try{ rs.close();} catch(SQLException e){};
if(conn != null) try{ conn.close();} catch(SQLException e){};
}
return item;
}
after COLLATE NOCASE use semi-column
"SELECT * FROM " + tableName + " WHERE " + columnName + "= ? COLLATE NOCASE;";

How to create a table in access database using java

i need to create a table in access database. For this i tried with the following code
public class Testac {
public static void main(String[] args) {
try {
System.out.println("Begining conn");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String accessFileName = "Centre";
String connURL = "jdbc:odbc:;DRIVER=Microsoft Access Driver (*.accdb);DBQ=" + accessFileName + ".accdb;PWD=";
Connection con = DriverManager.getConnection(connURL, "", "");
Statement stmt = con.createStatement();
System.out.println("Conn done succesfully");
stmt.execute("create table student ( Name string, ID integer )"); // create a student
stmt.execute("insert into student values(‘Md. SHAHJALAL’, ‘02223540’)"); // insert data into student
stmt.execute("select * from student"); // execute query in table student
ResultSet rs = stmt.getResultSet(); // get any Resultt that came from our query
if (rs != null) {
while (rs.next()) {
System.out.println("Name: " + rs.getString("Name") + " ID: " + rs.getString("ID"));
}
}
stmt.close();
con.close();
} catch (Exception err) {
System.out.println("ERROR: " + err);
}
}
}
But it throws the following error " ERROR: java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified ".
It is possible with UCanAccess
con = ConnectMdb(homedirectory+"/"+"Centre.accdb");
if (con != null) {
Statement st3 = null;
try {
st3 = (Statement) con.createStatement();
} catch (SQLException ex) {
Logger.getLogger(DataEntryScreen.class.getName()).log(Level.SEVERE, null, ex);
}
String sqlq3 = "CREATE TABLE REGISTRATION " +
"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))";
// System.out.println(sqlq1);
// ResultSet rs3 = null;
try {
st3.execute(sqlq3);
} catch (SQLException ex) {
Logger.getLogger(DataEntryScreen.class.getName()).log(Level.SEVERE, null, ex);
}
Try this.
Below Corrected Code may help you:
mistake in connection string and while creating table. need to use executeUpdate method
public class Testac {
public static void main(String[] args) {
try {
System.out.println("Begining conn");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String accessFileName = "Centre";
String connURL = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + accessFileName + ".accdb;PWD=";
Connection con = DriverManager.getConnection(connURL, "", "");
Statement stmt = con.createStatement();
System.out.println("Conn done succesfully");
stmt.executeUpdate("create table student ( Name string, ID integer )"); // create a student
stmt.execute("insert into student values(‘Md. SHAHJALAL’, ‘02223540’)"); // insert data into student
stmt.execute("select * from student"); // execute query in table student
ResultSet rs = stmt.getResultSet(); // get any Resultt that came from our query
if (rs != null) {
while (rs.next()) {
System.out.println("Name: " + rs.getString("Name") + " ID: " + rs.getString("ID"));
}
}
stmt.close();
con.close();
} catch (Exception err) {
System.out.println("ERROR: " + err);
}
}
}
The problem is on this line:
String connURL = "jdbc:odbc:;DRIVER=Microsoft Access Driver (*.accdb);DBQ=" + accessFileName + ".accdb;PWD=";
which you should change to:
String connURL = "jdbc:odbc:DRIVER=Microsoft Access Driver (*.accdb);DBQ=" + accessFileName + ".accdb;PWD=";
i.e. you need to remove the semi-colon between jdbc and odbc.

Show table names in MySQL database and the count of their records

I'm working on the next step of the class assignment and I want to do a query where I pull the metadata from the database to list the tables in it then include the count of records in the tables. I have it where it kind of works but in the first half shown it only puts a number 1 where the count of records should go. In the second half (I'm doing this for testing purposes now and will only have the first half if I can get it to work) it prints out the number of records just fine but I have the table name hard coded in. I want it to be able to read in the table name from the metadata result then execute the query for the count of records. I am running this in netbeans with a MySQL database and am using the JDBC driver.
connect();
try
{
String db = conn.getCatalog();
data.append("The current database " + db + " contains the following tables:\r\n");
}
catch(Exception err)
{
System.out.print(err + "\r\n");
}
try
{
ResultSet rs = null;
DatabaseMetaData md = conn.getMetaData();
rs = md.getTables(null, null, "%", null);
while (rs.next())
{
String tbl = rs.getString(3);
System.out.print(tbl + "\r\n");
ResultSet ct = null;
ct = conn.createStatement().executeQuery("SELECT COUNT(*) FROM" + tbl);
while (ct.next())
{
System.out.print(ct.getString(1) + "\r\n");
data.append("Table \"" + rs.getString(3) + "\" contains " + ct.getString(1) + " records.\r\n");
}
}
data.append("\r\n");
}
catch(Exception err)
{
System.out.print(err + "\r\n");
}
try
{
ResultSet ct = null;
ct = conn.createStatement().executeQuery("SELECT COUNT(*) FROM customer");
while (ct.next())
{
data.append(ct.getString(1) + "\r\n");
}
ResultSet pt = null;
pt = conn.createStatement().executeQuery("SELECT COUNT(*) FROM product");
while (pt.next())
{
data.append(pt.getString(1) + "\r\n");
}
}
catch(Exception err)
{
System.out.print(err + "\r\n");
}
With following query you can query all tables with number of rows, date size, index size etc on a specific database.
SELECT concat(table_schema,'.',table_name) tables,
concat(round(table_rows),'') rows,
concat(round(data_length/(1024),2),'') data_size,
concat(round(index_length/(1024),2),'') index_size,
concat(round((data_length+index_length)/(1024),2),'') total_size,
round(index_length/data_length,2) index_data_ratio
FROM information_schema.TABLES
WHERE table_schema like "%YOUR-DATABASE-NAME-HERE%"
ORDER BY rows DESC LIMIT 20;
This is what I ended up doing and it works exactly as I wanted. I ended up using a prepared statement in the while loop to make it work.
connect();
try
{
String db = conn.getCatalog();
data.append("The current database " + db + " contains the following tables:\r\n");
}
catch(Exception err)
{
System.out.print(err + "\r\n");
}
try
{
ResultSet rs = null;
DatabaseMetaData md = conn.getMetaData();
rs = md.getTables(null, null, "%", null);
while (rs.next())
{
String tbl = rs.getString(3);
String query = ("SELECT COUNT(*) FROM " + tbl);
PreparedStatement cnt = conn.prepareStatement(query);
ResultSet ct = cnt.executeQuery();
while (ct.next())
{
data.append("Table " + rs.getString(3) + " has " + ct.getString(1) + " records\r\n");
}
}
data.append("\r\n");
}
catch(Exception err)
{
System.out.print(err + "\r\n");
}

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