JavaFX delete datarow in tableview and sqlite - 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());
}
}

Related

select rows between two dates in sqlite using java

select rows between two dates in sqlite using java.
When i try to retrieve rows between to two dates from sqlite database in javafx program i always get one row from the whole rows even if there is multiple rows it select the first row and discard the remaining or not included in the result set at all, how can solve this problem and again the database has some records but the query always return the first one
#FXML
private void report(ActionEvent event)
{
if(searchfromDate.getValue() != null && searchToDate.getValue() != null)
{
try
{
DBconnector.connect();
LocalDate startDate = searchfromDate.getValue();
LocalDate endDate = searchToDate.getValue();
String query = "select * from selled where date between '" + startDate
+ "' and '" + endDate + "'";
ResultSet rs = DBconnector.query(query);
Alert alert = new Alert(AlertType.INFORMATION);
JSONObject file = new JSONObject();
if(rs.next())
{
int id = rs.getInt("id");
String customer = rs.getString("costomer");
String name = rs.getString("name");
String barcode = rs.getString("barcode");
int amount = rs.getInt("amount");
LocalDate date = LocalDate.parse(rs.getString("date"));
double price = rs.getDouble("price");
String garentee = rs.getString("garentee");
file.put("id", id);
file.put("customer", customer);
file.put("name", name);
file.put("barcode", barcode);
file.put("amount", amount);
file.put("date", date);
file.put("price", price);
file.put("garentee", garentee);
}
FileWriter writer = new FileWriter("تقرير المبيعات.json");
writer.write(file.toString());
writer.flush();
writer.close();
alert.setTitle("رسالة تاكيد");
alert.setHeaderText(null);
alert.setContentText("تم استخراج الملف بنجاح");
alert.showAndWait();
Desktop desktop = Desktop.getDesktop();
desktop.browse(new URI("https://arabsefr.com/save-report?fbclid=IwAR2ON1Tl8ETQ--3QEAVFJLMjTuWUhpLCZrD3PXhg8TZpdlUH4umKBfl78OM"));
}
catch (Exception ex)
{
System.out.println(ex);
}
}
else
{
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("رسالة تاكيد");
alert.setHeaderText(null);
alert.setContentText("لم يتم تحديد التاريخ");
alert.showAndWait();
}
}
When you are using SQLite, use of strftime() method is always recommended while manipulating with dates this makes sure that future troubles are avoided.
WHERE strftime('%s', date) between strftime('%s', startDate) and strftime('%s', endDate)

SQLITE JDBC driver prepared statement fails (internal pointer 0)

SQLite JDBC driver version 3.21.0 (the latest).
Summary
A prepared statement is opened for multiple insert operations on a table, but is unable to survive primary key violations.
If one "bad" insert fails due to a Primary Key violation, the prepared statement is unable to process subsequent "good" inserts. An exception "statement is not executing" is raised when calling pstmt.setString().
Tracing the error into org.Sqlite.core.CorePreparedStatement the call is failing in checkOpen() pointer==0.
Example is below.
Does anyone know why this is happening? I see a similar bug report was raised but supposedly fixed.
Connection conn = DriverManager.getConnection("jdbc:sqlite:./test.db");
String createtable = "CREATE TABLE dummy(ID text, VAL text, PRIMARY KEY(ID) )";
String psSQL = "INSERT INTO dummy (ID, VAL) VALUES (?,?)";
String id = "123456789";
String val = "FooBar";
String id2 = "123456789";
String val2 = "FooBar2";
String id3 = "345678901";
String val3 = "FooBar3";
try {
Statement st= conn.createStatement();
st.executeUpdate(createtable);
PreparedStatement pst = conn.prepareStatement(psSQL);
// 1 insert good entry
pst.setString(1, id);
pst.setString(2, val);
pst.executeUpdate();
System.out.println("1st insert OK for " + id);
// 2. try to insert bad duplicate entry with pkey violation
try {
pst.setString(1, id);
pst.setString(2, val);
pst.executeUpdate();
System.out.println("2nd insert OK for " + id);
} catch (SQLException e) {
System.out.println("2nd insert Failed for " + id);
e.printStackTrace();
}
// 3. try to insert 3rd good value
try {
pst.setString(1, id3); // exception raised here
pst.setString(2, val3);
pst.executeUpdate();
System.out.println("3 insert OK for " + id3);
} catch (SQLException e) {
System.out.println("3 insert Failed for " + id3);
e.printStackTrace();
}
pst.close();
st.executeUpdate(droptable);
} catch (SQLException e) {
e.printStackTrace();
}
This bug has been fixed in sqlite-jdbc version 3.25.2, see https://github.com/xerial/sqlite-jdbc#news.

Delete from command not working in sqlite?

I have a sqlite db file. I am using DB Browser for Sqlite as the client. I went in and ran delete from command on most of my tables. Thereafter I tried to export using the option Database to SQL file I notice all my data is appearing in it. What I wondering is that why the data have not been deleted? I know the sqlite file size will not shrink.
Below is snippet of my codes.
string str = #"Data Source=" + userFilePath + "\\mysqlite.sqlite3";
using (SQLiteConnection con = new SQLiteConnection(str))
{
con.Open();
SQLiteTransaction trans = con.BeginTransaction();
try
{
String cmdSelect1 = "Select * from table1 where companyID='" + companyID + "' And month='" + month + "' And year='" + year + "'";
int fiscalPeriod = Convert.ToInt32(monthNumber);
int financialYear = Convert.ToInt32(itemvalueyear);
using (SQLiteCommand cmd1 = new SQLiteCommand(cmdSelect1, con, trans))
{
SQLiteDataReader dr1 = cmd1.ExecuteReader();
if (dr1.Read())
{
MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show("Records Already Exist ? Are you confirm replace it?", "Delete Confirmation", System.Windows.MessageBoxButton.YesNo);
if (messageBoxResult == MessageBoxResult.Yes)
{
String deleteTable = "Delete from table1 where companyID='" + companyID + "' And month='" + month + "' And year='" + year + "'";
using (SQLiteCommand cmdDeleteTb1 = new SQLiteCommand(deleteTable, con, trans))
{
cmdDeleteTb1.ExecuteNonQuery();
cmdDeleteTb1.Dispose();
}
foreach (object line in linesC)
{
if (line.GetType() == typeof(TypeC))
{
String cmdText2 = "INSERT INTO table1(tbID,companyID,month,year) VALUES(#tbID,#companyID,#month,#year)";
using (SQLiteCommand cmd = new SQLiteCommand(cmdText2, con, trans))
{
cmd.Parameters.AddWithValue("#tbID", tbID);
cmd.Parameters.AddWithValue("#companyID", companyID);
cmd.Parameters.AddWithValue("#month", month);
cmd.Parameters.AddWithValue("#year", year);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.Dispose();
}
}
}
}
}
dr1.Close();
cmd1.Dispose();
}
trans.Commit();
MessageBox.Show("Successfully Inserted Into Database");
}
catch (Exception ex)
{
MessageBox.Show("Rollback " + ex.ToString());
trans.Rollback();
}
con.Close();
con.Dispose();
GC.Collect();
Ok:
It appears you are beginning two transactions. You begin your loop inserts after you begin your delete.
Commit your Delete transaction and then later commit your inserts.
This is than committing after beginning both transactions.

SQLite test if record exists

I am struggling with testing if there is specific data in my SQLite database.
The method accepts a subject code, person id, and a table name. I am 100% sure those 3 things are correct.
What this should do is try to select a record. If the record can be selected return -1, otherwise return 0.
My problem is the datareader does not seem to be reading any records, when there is records in my database.
public int TestIfExists(string subID, string personID, string table)
{
_sqlConnection = new SQLiteConnection(_conStr);
bool dataRead = false;
int rc = 0;
try
{
string selectQuery = "SELECT * FROM " + table + " WHERE PersonID = '" +
personID + "' AND SubjectCode = '" + subID + "'";
_sqlConnection.Open();
SQLiteCommand sqlCommand = new SQLiteCommand(selectQuery, _sqlConnection);
IDataReader idr = sqlCommand.ExecuteReader();
dataRead = idr.Read();
if (dataRead == true)
{
rc = -1;
}//end if
else
{
rc = 0;
}//end else
idr.Close(); // Closed IDataReader
}//end try
catch (SQLiteException sqlEx) // Catch SQLiteException
{
MessageBox.Show(sqlEx.ToString());
throw new DataStoreError(sqlEx.Message);
}//end catch
catch (Exception ex)
{
throw ex;
}//end catch
finally
{
_sqlConnection.Close();
}//end finally
return rc; //Single return
}
When you are trying to see if it exists or no, you can do a
SELECT Count(*) FROM Table WHERE (...)
and this way 0 would means doesn't exists, other wise yes.

what is wrong with this C# duplicate row code?

I'm trying to duplicate a record in my database and I used this code you see below, the sql query worked perfectly in sql server but here I don't know what the problem...help me please
//Insert new Order
int newOrderId = 0;
if (e.CommandName == "Repeat")
{
try
{
SqlConnection con = DataAccess.Connection.GetDBConnection();
//duplicate the jobs from the old order to the new added order
sqlCmd.Parameters.Clear();
string com2 = "Insert Into [OrderItems] (orderId, productId, quantity, [length], note, multipleSlip, internalDiameter, " +
"wall, machineReCuttingId,winderId, jobNote) (select #newOrderId, productId, quantity, [length], note, multipleSlip, " +
"internalDiameter, wall, machineReCuttingId, winderId, jobNote FROM OrderItems Where orderId=#oldOrderId)";
SqlCommand sqlCmd = new SqlCommand(com2, con);
sqlCmd.Parameters.Add("#newOrderId", SqlDbType.Int).Value = newOrderId;
//assign the old order Id to the insert parameter #oldOrderId
sqlCmd.Parameters.Add("#oldOrderId", SqlDbType.Int).Value = Convert.ToInt32(e.CommandArgument);
sqlCmd.ExecuteNonQuery();
StatusLabel.Text = "The New Order is" + newOrderId.ToString() + " The Old order ID is: " + e.CommandArgument.ToString();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
OrderGridView.DataSource = ViewDataSource(selectCustomer);
OrderGridView.DataBind();
// Response.Redirect("../Orders/AddNewOrder.aspx?customerId=" + selectCustomer + "&" + "orderId=" + newOrderId);
}
By the way I tested the values of newOrderId and the oldOrderId they are both correct

Resources