Update a column if row exists, and insert row if it doesn't - sqlite

I have a table INVENTORY with 2 columns [product(primary key) - quantity]. I want to insert to this table a product with its quantity.
public boolean insertPackage(String product, int quantity)
throws SQLException, ClassNotFoundException {
System.out.println("Insert product to Invetory");
boolean flag=false;
sq = "INSERT INTO INVENTORY VALUES (?, ?)";
try {
Class.forName(typeDB);
c = DriverManager.getConnection(path);
stm = c.prepareStatement(sq);
PreparedStatement stm = c.prepareStatement(sq);
stm.setString(1, product);
stm.setInt(2, quantity);
int rowsAffected = stm.executeUpdate();
} catch (SQLException e) {
//There is already a same product in the Inventory
flag = true;
System.out.println(e.getMessage());
} finally {
if (stm != null)
stm.close();
if (c != null)
c.close();
}
return flag; //if the flag is true, then execute insert.
}
If it returns true, then I search for this product, retrieve the quantity and then update the table with the new quantity. I am wondering if this way I thought, is a good way to check how to perform the insertion or there is a better one.

In your particular case the easiest solution would be to use SQLite's INSERT OR REPLACE syntax, like so:
public static void main(String[] args) {
String connectionURL = "jdbc:sqlite:"; // in-memory database
try (Connection conn = DriverManager.getConnection(connectionURL)) {
// set up test data
try (Statement st = conn.createStatement()) {
st.execute("CREATE TABLE INVENTORY (product VARCHAR(10) PRIMARY KEY, quantity INT)");
st.execute("INSERT INTO INVENTORY (product, quantity) VALUES ('one', 123)");
}
System.out.println("Initial state:");
dumpTable(conn);
// real code starts here
String sql = "INSERT OR REPLACE INTO INVENTORY (product, quantity) VALUES (?, ?)";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, "two"); // product is new, so it will insert
ps.setInt(2, 234);
ps.executeUpdate();
System.out.println();
System.out.println("First change:");
dumpTable(conn);
ps.setString(1, "one"); // product already exists, so it will replace
ps.setInt(2, 999);
ps.executeUpdate();
System.out.println();
System.out.println("Second change:");
dumpTable(conn);
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
private static void dumpTable(Connection conn) throws SQLException {
try (
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT product, quantity FROM INVENTORY ORDER BY product")) {
while (rs.next()) {
System.out.printf(
"product \"%s\" - quantity: %d%n",
rs.getString("product"),
rs.getInt("quantity"));
}
}
}
However, INSERT OR REPLACE in SQLite is really just a DELETE followed by INSERT, so another solution would be to try and do the UPDATE first, then do an INSERT if the UPDATE doesn't affect any rows. (That might be more efficient if you tend to be doing more updates than inserts.)
public static void main(String[] args) {
String connectionURL = "jdbc:sqlite:"; // in-memory database
try (Connection conn = DriverManager.getConnection(connectionURL)) {
// set up test data
try (Statement st = conn.createStatement()) {
st.execute("CREATE TABLE INVENTORY (product VARCHAR(10) PRIMARY KEY, quantity INT)");
st.execute("INSERT INTO INVENTORY (product, quantity) VALUES ('one', 123)");
}
System.out.println("Initial state:");
dumpTable(conn);
// real code starts here
updateQuantity("two", 234, conn);
System.out.println();
System.out.println("First update:");
dumpTable(conn);
updateQuantity("one", 999, conn);
System.out.println();
System.out.println("Second update:");
dumpTable(conn);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
private static void updateQuantity(String theProduct, int newQuantity, Connection conn) throws SQLException {
int rowsAffected;
try (PreparedStatement psUpdate = conn.prepareStatement("UPDATE INVENTORY SET quantity=? WHERE product=?")) {
psUpdate.setInt(1, newQuantity);
psUpdate.setString(2, theProduct);
rowsAffected = psUpdate.executeUpdate();
}
if (rowsAffected == 0) {
try (PreparedStatement psInsert = conn.prepareStatement("INSERT INTO INVENTORY (product, quantity) VALUES (?, ?)")) {
psInsert.setString(1, theProduct);
psInsert.setInt(2, newQuantity);
psInsert.executeUpdate();
}
}
}
private static void dumpTable(Connection conn) throws SQLException {
try (
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT product, quantity FROM INVENTORY ORDER BY product")) {
while (rs.next()) {
System.out.printf(
"product \"%s\" - quantity: %d%n",
rs.getString("product"),
rs.getInt("quantity"));
}
}
}
In both cases we see:
Initial state:
product "one" - quantity: 123
First update:
product "one" - quantity: 123
product "two" - quantity: 234
Second update:
product "one" - quantity: 999
product "two" - quantity: 234

This is not a good way to check if a product exists because:
-There are many other things that can go wrong ( a lot of different SQLExceptions, not only PK violation ) and you will end up with a true flag.
-You should not use exceptions for something that is normal to happen.
-Throwing and catching an exception is slow.
Try this:
1) select from INVENTORY by product using count:
select count(*) from INVENTORY where product = ?
2) if the count is equal to 0 then execute the insert
else increment the quantity.

Related

JavaFX delete datarow in tableview and sqlite

I would like to delete a row in tableview but also in the
underlying SQLite Database which populate the tableview
Here I get the selectedRow
public void deleteDBRow() {
if (tableV.getSelectionModel().getSelectedItem() != null) {
Bew selBew = tableV.getSelectionModel().getSelectedItem();
System.out.println(selBew.getName());
}
}
and can delete it with casual code
DELETE FROM Table WHERE name = ""+selBew.getName()");
But I would like to delete the entry in the sqlite database also
From time to time I have rows with the same text in every column - so this way
was critical - can I use rowID to delete the selected row in sqlite?
Here one try from me to get rowid in tableview
ObservableList bewList = FXCollections.observableArrayList();
try {
String sql = "SELECT rowID, Name, Date, Action, Info FROM tab1";
Connection conn = DriverManager.getConnection("jdbc:sqlite:TestB1.db");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
bewList.add(new Bew(rs.getInt("rowID"), rs.getString("name"), rs.getString("date"),
rs.getString("action"), rs.getString("Info")));
System.out.println("rs.next : " + rs.getInt("rowID") +" - " + rs.getString("date") +" " +
rs.getString("action") +" " + rs.getString("Info"));
}
}catch (Exception e) {
System.out.println("SQLiteDB.getData ---> Error RS");
System.err.println("*E"+e.getClass().getName() + ": " + e.getMessage());
}
return bewList;
String sql = "CREATE TABLE IF NOT EXISTS tab1" +
"(rowID INT PRIMARY KEY," +
"NAME CHAR(50) NOT NULL ,"+
"DATE CHAR(15) ,"+
"ACTION CHAR(50) ,"+
"INFO CHAR(3));";
conn.createStatement().executeUpdate(sql);
rowID ist always 0 - don't know why ???
edit:
Controller
ObservableList bewList = DB.getData();
tableV.setItems(bewList);
Edit:
Maybe error in here - add data
i add 4 values - rowid missing??
public void add(String Name, String Date, String Action, String Info) {
try {
Connection conn = DriverManager.getConnection("jdbc:sqlite:TestB2.db");
stmt = conn.createStatement();
String ValStr = "\'"+Name+"\' ,\'"+Date+"\',\'"+Action+"\' ,\'"+Info+"\'";
String sql = "INSERT INTO tab1 (rowID, NAME,DATE,ACTION, INFO) VALUES ("+ValStr+")";
// System.out.println("Button Click add"+conn.createStatement().toString());
stmt.executeUpdate(sql); //geƤndert
ObservableList<Bew> list = getData();
conn.close();
System.out.println("DB ROW add");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}

JavaFX combo box repeating the same value set

I used a combo box to retrieve data from MySQL database. But when i inserted the first value set to database, combo box values are repeating. I want to know why it is happening and how to avoid it. i called this method on main. Thanks
public void FillCombo(){
try{
String sql = "Select Name from Employee where Position='Driver'";
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()){
op.add(rs.getString("Name"));
}
selectDriverC.setItems(op);
pst.close();
rs.close();
}
catch(Exception e){
System.out.println(e);
}
}
Add a condition that checks if the String you wanna insert is already in op,
I assume op type is ObservableList<String>. This should work :
public void FillCombo(){
try{
String sql = "Select Name from Employee where Position='Driver'";
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()){
if(!op.contains(rs.getString("Name"))
add(rs.getString("Name"));
}
selectDriverC.setItems(op);
pst.close();
rs.close();
}
catch(Exception e){
System.out.println(e);
}
}

Count deleted records, returns 0

I perform a DELETE in my table from my servlet by calling a method action.deleteBox(box); which executes the delete function
deleteBox method
Connection c = null;
PreparedStatement stm = null;
sq = "DELETE FROM BOXES WHERE ...";
try {
Class.forName(typeDB);
c = DriverManager.getConnection(path);
stm = c.prepareStatement(sq);
//...
stm.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
System.out.println("my stm is closed : " + stm.isClosed());
if (stm != null)
stm.close();
if (c != null)
c.close();
}
the delete is executed fine. Then I want to check how many records were deleted from the previous delete: So I call this method:
public int countDeletesRecords()
throws SQLException, ClassNotFoundException {
Connection c = null;
PreparedStatement stm = null;
sq = "SELECT changes() as \"deletedRows\" ";
int deletedRows=-1;
try {
Class.forName(typeDB);
c = DriverManager.getConnection(path);
stm = c.prepareStatement(sq);
ResultSet rs = stm.executeQuery();
if (rs.next()) {
deletedRows = rs.getInt("deletedRows");
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
System.out.println("my stm is closed : " + stm.isClosed());
if (stm != null)
stm.close();
if (c != null)
c.close();
}
return deletedRows; //I get 0..
}
and I get 0, while 1 records where deleted.
While this does not directly answer the question an alternative, simpler, approach would capture the return value of executeUpdate(), that returns the number of affected (in this case, deleted) rows:
final int deletedRowCount = stm.executeUpdate();
The documentation says:
This function returns the number of rows modified, inserted or deleted by the most recently completed INSERT, UPDATE or DELETE statement on the database connection
You are creating a new database connection in which no DELETE statement was ever executed.

Unable to update DB by form data

please give me advice! I get form data in servlet and try to update the database, but it doesn't works. There is connection with database (without servlet code any data is properly added in db), but no any exception are thrown. The servlet get parameters - they are available in JSP by EL-expressions. I tried to update the db simply by statement, without using preparedStatement but it didn't help. Here it is the code:
public class ServletClass extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
DBConn dbConn = new DBConn();
String number = req.getParameter("number");
String amount = req.getParameter("amount");
String date = req.getParameter("date");
ArrayList list = dbConn.returnList(number, amount, date);
req.setAttribute("attr", list);
RequestDispatcher requestDispatcher = req.getRequestDispatcher("index.jsp");
requestDispatcher.forward(req, resp);
}
}
public class DBConn {
public ArrayList<InvoicesBean> returnList(String number, String amount, String date) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
ArrayList<InvoicesBean> beanList = new ArrayList<InvoicesBean>();
PreparedStatement preparedStatement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ved", "root", "1111");
statement = connection.createStatement();
preparedStatement = connection.prepareStatement("insert into invoices values(?, ?, ?);");
preparedStatement.setString(1, number);
preparedStatement.setString(2, amount);
preparedStatement.setString(3, date);
preparedStatement.executeUpdate();
resultSet = statement.executeQuery("SELECT * FROM invoices;");
while (resultSet.next()){
InvoicesBean invoicesBean = new InvoicesBean();
invoicesBean.setNumber(resultSet.getString("number"));
invoicesBean.setAmount(resultSet.getString("amount"));
invoicesBean.setDate(resultSet.getString("date"));
beanList.add(invoicesBean);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (resultSet != null) resultSet.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return beanList;
}
}
InvoiceBean-class is just a standard bean class with getters/setters
invoicesBean.setNumber(resultSet.getString("number"));
invoicesBean.setAmount(resultSet.getString("amount"));
invoicesBean.setDate(resultSet.getString("date"));
You can not have the database column names as 'number' or 'date'. they are reserved.
check the column names again.
for checking if this is the error, you can replace the column names by column numbers 1,2,3.

Error connecting to databasehandler

I have a error regarding database as shown below:
E/CursorWindow(386): Bad request for field slot 0,-1. numRows = 1, numColumns = 63
here's my piece of code:
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_IMAGE = "image";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_IMAGE + " BLOB,"
+ KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addContact(Methods contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_IMAGE,contact.getImageId());
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Methods getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,KEY_IMAGE,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Methods contact = new Methods(Integer.parseInt(cursor.getString(cursor.getColumnIndex(KEY_ID))),
cursor.getBlob(cursor.getColumnIndex(KEY_IMAGE)),cursor.getString(cursor.getColumnIndex(KEY_NAME)), cursor.getString(cursor.getColumnIndex(KEY_PH_NO)));
// return contact
cursor.close();
return contact;
}
// Getting All Contacts
public List<Methods> getAllContacts() {
List<Methods> contactList = new ArrayList<Methods>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Methods contact = new Methods();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setImageId(cursor.getBlob(1));
contact.setName(cursor.getString(2));
contact.setPhoneNumber(cursor.getString(3));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return contact list
return contactList;
}
/*// Updating single contact
public int updateContact(Methods contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}*/
// Deleting single contact
public void deleteContact(Methods contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
Log.v("deleteContact", "Deleted row is: "+String.valueOf(contact.getID()));
}
void deleteAll(Methods contact)
{
SQLiteDatabase db= this.getWritableDatabase();
db.delete(TABLE_CONTACTS, null, null);
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
It would help to have more information here (a stack trace perhaps?). However it seems you're not providing an "id" when adding a contact. Consider making this column auto incrementing instead.
Last, if this is an Android question, your primary key column should be auto incrementing and should be called "_id", else make sure that this is given as a column name in any cursor returned from a query. Also check that your database has a table called "android_metadata" too.

Resources