javafx how to refresh table after adding record - javafx

i saw so many answers but its not suitable with me because i am using loop to generate my table not specific class
i want to refresh the table who generate the data from a loop.
i tried to refresh table but now working
i tried to build date again but it duplicates the table
Here is where cells generated by a loop
while(rs.next()){
//Iterate Row
ObservableList<String> row = FXCollections.observableArrayList();
for(int i=1 ; i<=rs.getMetaData().getColumnCount(); i++){
//Iterate Column
row.add(rs.getString(i));
}
System.out.println("Row [1] added "+row );
data.add(row);
table.setItems(data);
}
Here is add button
buttonAdd.setOnAction(new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent t){
try {
stmt.executeUpdate("INSERT into stock VALUES('"
+ fieldCategoryID.getText()+ "','" + fieldCategoryName.getText() + "','" + fieldAmount.getText() + "','" + fieldCostPrice.getText()+ "','" + fieldSellingPrice.getText()
+ "','" + fieldCategoryProfit.getText()+ "','" + fieldSupplier.getText()+ "','" + fieldCategoryProfitRate.getText()+
"','" + fieldTotalCategoryProfit.getText()+"','" + fieldOnStock.getText()+ "')");
content.getChildren().removeAll(table);
table.refresh();
content.getChildren().add(table);
} catch (SQLException ex) {
Logger.getLogger(Stock.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
Here is delete button
buttonDelete.setOnAction(new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent t){
try {
Alert alertConfirmation = new
table.getSelectionModel().getSelectedIndex();
TablePosition pos = (TablePosition) table.getSelectionModel().getSelectedCells().get(0);
int row = pos.getRow();
TableColumn col = pos.getTableColumn();
String data = (String) col.getCellObservableValue(table.getItems().get(row)).getValue();
String query = "DELETE FROM stock where category_code = ?";
pst = con.prepareStatement(query);
pst.setString(1, data);
pst.execute();
}

i add a refresh method that clear observableList data Then i declare Statement and ResultSet again then added rows again
public void refreshTable() throws SQLException{
data.clear();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery("select * from stock");
while(rs.next()){
//Iterate Row
row = FXCollections.observableArrayList();
for(int i=1 ; i<=rs.getMetaData().getColumnCount(); i++){
//Iterate Column
row.add(rs.getString(i));
}
System.out.println("Row [1] added "+row );
data.add(row);
table.setItems(data);
}
}

Related

Oracle "UPDATE" command returns 0 rows affected in my ASP .NET application but the SQL statement itself works in PL/SQL

I have this ASP.NET project working with Oracle, I have the following code for operating the DB:
public int cmd_Execute_Orcl(string strSql, params OracleParameter[] paramArray)
{
OracleCommand myCmd = new OracleCommand();
try
{
myCmd.Connection = myOrclConn;
myCmd.CommandText = strSql;
foreach (OracleParameter temp in paramArray)
{
myCmd.Parameters.Add(temp);
}
ConnectionManage(true);
int i = myCmd.ExecuteNonQuery();
myCmd.Parameters.Clear();
return i;
}
catch (Exception ex)
{
throw (ex);
}
finally
{
myCmd.Dispose();
ConnectionManage(false);
}
}
"ConnectionManage()" turns on or off the connection, the following code is from data access layer of the program:
public string Edit_DAL(string id, string jh, string jz, string jd, string wd, string gzwz, string qxlx, string sx, string jx, string jb, string cfdd, string zjqssj, string zjzzsj, string bz)
{
string sql = "update JH set jh = :jh, jz = :jz, wd = :wd, jd = :jd, gzwz = :gzwz, qxlx = :qxlx, sx = :sx, jx = :jx, jb = :jb, cfdd = :cfdd, zjqssj = TO_DATE(:zjqssj, 'yyyy-mm-dd hh24:mi:ss'), zjzzsj = TO_DATE(:zjzzsj, 'yyyy-mm-dd hh24:mi:ss'), bz = :bz where ID = :idy";
string result = null;
{
String[] temp1 = zjqssj.Split('/');
String[] temp2 = zjzzsj.Split('/');
string tempString = "";
if (temp1[2].Length < 2)
{
temp1[2] = temp1[2].Insert(0, "0");
}
for (int i = 0; i < temp1.Length; i++)
{
if (i != 0)
{
temp1[i] = temp1[i].Insert(0, "/");
}
tempString += temp1[i].ToString();
}
zjqssj = tempString;
tempString = "";
if (temp2[2].Length < 2)
{
temp2[2] = temp2[2].Insert(0, "0");
}
for (int i = 0; i < temp2.Length; i++)
{
if (i != 0)
{
temp2[i] = temp2[i].Insert(0, "/");
}
tempString += temp2[i].ToString();
}
zjzzsj = tempString;
tempString = "";
}
OracleParameter[] pars ={
new OracleParameter(":idy",id),
new OracleParameter(":jh",jh),
new OracleParameter(":jz",jz),
new OracleParameter(":jd",jd),
new OracleParameter(":wd",wd),
new OracleParameter(":gzwz",gzwz),
new OracleParameter(":qxlx",qxlx),
new OracleParameter(":sx",sx),
new OracleParameter(":jx",jx),
new OracleParameter(":jb",jb),
new OracleParameter(":cfdd",cfdd),
new OracleParameter(":zjqssj",(zjqssj.Replace('/', '-') + " 00:00:00")),
new OracleParameter(":zjzzsj",(zjzzsj.Replace('/', '-') + " 00:00:00")),
new OracleParameter(":bz",bz)
};
try
{
SqlHelper.cmd_Execute_Orcl(sql, pars);
result = "ok";
}
catch (Exception ex)
{
result = "no" + "=" + ex.Message + "\n" + ex.StackTrace;
}
return result;
}
Here's where the strange thing happens, when I hit this part of the code, there's no exception, it returns 0, no rows affected, all the values of the parameters are normal, with expected value, then I tried to run the command in PL/SQL and it works, the row is correctly updated, delete function is also referencing the same "cmd_Execute_Orcl" method and it works just fine, and for the other object the edit function is working perfectly, I am posting the code below:
public string Edit(string OriginalId, string EditUserAccount, string EditUserName, string EditUserMobile, string EditDeptId, string EditRoleId, string EditRoleName)
{
string sql = "update AuthUser set UserAccount=:EditUserAccount, UserName=:EditUserName, UserMobile=:EditUserMobile, DepartmentId=:EditDeptId, RID=:EditRoleId, RoleName=:EditRoleName where ID=:OriginalId";
OracleParameter[] pars ={
new OracleParameter(":EditUserAccount",EditUserAccount),
new OracleParameter(":EditUserName",EditUserName),
new OracleParameter(":EditUserMobile",EditUserMobile),
new OracleParameter(":EditDeptId",EditDeptId),
new OracleParameter(":EditRoleId",EditRoleId),
new OracleParameter(":EditRoleName",EditRoleName),
new OracleParameter(":OriginalId",OriginalId),
};
try
{
SqlHelper.cmd_Execute_Orcl(sql, pars);
return "ok";
}
catch (Exception ex)
{
string test = ex.Message;
return "no";
}
}
In the expected table, column ID is nvarchar2 with default value of sys_guid(), column ZJQSSJ and column ZJZZSJ is of type date, all other columns are of type varchar2, I have also tried executing "COMMIT" and reformating data for date, but the same problem is still there, plz help...

Retrieving Int Value from SQLite database

I am trying to retrieve an integer from my SQLite database and my current query crashes my program. This is what I have so far:
*/
public int getWin(String id){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT " + COL3 + " FROM " + TABLE_NAME +
" WHERE " + COL2 + " = '" + id + "'";
Log.d(TAG, "updateName: query: " + query);
db.execSQL(query);
int win = Integer.parseInt(query);
return win;
}
I am not sure why this will not work. Thanks in advance.
You are trying to convert the value SELECT ......... into a number as per int win = Integer.parseInt(query);.
For a SELECT statment you need you need to retrieve a Cursor (result set), via either the query or rawQuery SQLiteDatabase method and then extract the value(s) from the method and to then access the respective column from the respective row(s).
I believe that you would use something like :-
public int getWin(String id){
SQLiteDatabase db = this.getWritableDatabase();
int rv = -1; //<<<<<<<<<< ADDED default value to return if no row found
String query = "SELECT " + COL3 + " FROM " + TABLE_NAME +
" WHERE " + COL2 + " = '" + id + "'";
Log.d(TAG, "updateName: query: " + query);
Cursor csr = db.rawQuery(query,null); //<<<<<<<<<< CHANGED to get the Cursor returned
// ADDED the following IF construct
if (csr.moveToFirst()) {
rv = csr.getInt(csr.getColumnIndex(COL3));
}
//int win = Integer.parseInt(query); //<<<<<<<<<< DELETED (commented out)
csr.close(); //<<<<<<<<<< ADDED should always close a Cursor when done with it
return rv; //<<<<<<<<<< return the value (-1 if no row found)
}
This assumes that you just want the value from a single row as identified by the WHERE clause.
If possible it is recommended to a) not build the query with direct values (makes it vulnerable to SQL Injection) and to b) utilise the convenience query method.
Apply both a and b and your code could be :-
public int getWin(String id){
SQLiteDatabase db = this.getWritableDatabase();
int rv = -1;
String whereclause = COL2 + "=?"; //<<<<<<<<<< where clause without where and ? for value that will be passed
String[] whereargs = new String[]{String.valueOf(id)}; //<<<<<<<<<< arguments used by the whereclause ? replaced on a 1 for 1 basis
String[] columns = new String[]{COL3}; //<<<<<<<<<< the columns to extract as a String array
Cursor csr = db.query(TABLE_NAME,columns,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv = csr.getInt(csr.getColumnIndex(COL3));
}
csr.close();
return rv;
}

How to get data row by date wise where i pass date picker's date and store data as long format date

When i call getAllInvoice(Date date) to get observable invoice list by passing date from date picker but it's return empty list please help how to get invoice observable list passing date picker's date where i store date as long format in database that example i provided below.
public VBox getBody() {
DatePicker datePicker = new DatePicker();
datePicker.setPrefWidth(width);
datePicker.setValue(LocalDate.now());
Calendar calendar = Calendar.getInstance();
calendar.set(datePicker.getValue().getYear(),datePicker.getValue().getMonthValue(),datePicker.getValue().getDayOfMonth());
ListView<String> invoiceListView = new ListView<>();
invoiceListView.setPrefWidth(width);
invoiceListView.setPrefHeight(550);
ObservableList<Invoice> invoiceObservableList = connection.getAllInvoice(Date.valueOf(datePicker.getValue()));
datePicker.valueProperty().addListener((observable, oldValue, newValue) -> {
invoiceObservableList.clear();
invoiceObservableList.addAll(connection.getAllInvoice(Date.valueOf(datePicker.getValue())));
});
ListChangeListener<Invoice> listener = new ListChangeListener<Invoice>() {
#Override
public void onChanged(Change<? extends Invoice> c) {
ObservableList<String> invoiceList = FXCollections.observableArrayList();
for (Invoice invoice : invoiceObservableList) {
Customer customer = connection.getCustomerById(invoice.getCustomerId());
invoiceList.add("#" + invoice.getId() + " - " + customer.getName() + " (" + customer.getNumber() + ")");
}
invoiceListView.setItems(invoiceList);
}
};
invoiceObservableList.addListener(listener);
ObservableList<String> invoiceList = FXCollections.observableArrayList();
for (Invoice invoice : invoiceObservableList) {
Customer customer = connection.getCustomerById(invoice.getCustomerId());
invoiceList.add("#" + invoice.getId() + " - " + customer.getName() + " (" + customer.getNumber() + ")");
}
invoiceListView.setItems(invoiceList);
VBox invoicePreview = new VBox();//addMe
invoicePreview.setPrefWidth(360);
invoicePreview.setPrefHeight(560);
invoicePreview.setAlignment(Pos.CENTER);
//invoicePreview.setStyle("-fx-background-color: green");
//invoicePreview.setPadding(new Insets(15));
invoiceListView.setOnMouseClicked(event -> {
if (event.getClickCount() == 2) {
invoicePreview.getChildren().clear();
invoicePreview.setAlignment(Pos.TOP_CENTER);
Invoice invoice = invoiceObservableList.get(invoiceListView.getSelectionModel().getSelectedIndex());
InvoicePreview preview = new InvoicePreview(invoice,sizer.getValue(100));
invoicePreview.getChildren().add(preview.printPreview());
}
});
Label massage = new Label("Please select invoice first.");
massage.setFont(new Font(invoiceWidth*5/100));
invoicePreview.getChildren().add(massage);
VBox leftVBox = new VBox(datePicker, invoiceListView);
leftVBox.setSpacing(5);
HBox mainBody = new HBox(leftVBox,invoicePreview);
mainBody.setSpacing(5);
VBox root = new VBox(mainBody);
root.setId("body");
return root;
}
and this is the Connection class's getAllInvoice(Date date) method that return observable invoice list,
public ObservableList<Invoice> getAllInvoice(Date date) {
long longDate = date.getTime();
ObservableList<Invoice> list = FXCollections.observableArrayList();
String query = "SELECT * FROM " + TABLE_INVOICE + " WHERE " + INVOICE_DATE + " LIKE \'"+longDate+"\'";
System.out.println(query);
try {
connection = DriverManager.getConnection("jdbc:sqlite:" + DATA_BASE);
Statement state = connection.createStatement();
ResultSet resultSet = state.executeQuery(query);
while (resultSet.next()) {
list.add(new Invoice(resultSet.getInt(INVOICE_ID), resultSet.getInt(INVOICE_USER_ID), resultSet.getInt(INVOICE_CUSTOMER_ID), resultSet.getLong(INVOICE_DATE)));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
}
return list;
}
datadase file like as:
"id" "uId" "cusId" "date"
-------------------------------
"3" "1" "4" "1524636334412"
"4" "1" "4" "1524636355419"
"5" "1" "3" "1524636411858"
"6" "1" "3" "1524637462701"
"7" "1" "4" "1524638110920"
how can i get data passing Date as a argument?
Assuming that you want records for the same date (day of the month of the year) as the date passed (long) then you could use :-
SELECT *
FROM invoice
WHERE date / 86400000 = <your_date> / 86400000
<your_date> being the date passed
This is stripping of the milliseconds (i.e. divide by 1000), then stripping of the seconds (i.e divide by another 60), then stripping off the minutes (i.e. divide by another 60) and then stripping of the hours (divide by 24)
i.e. 1000 * 60 * 60 * 24 = 86400000
Based upon your example data then (where 1524636334412 is the datetime of the first row):-
SELECT *
FROM invoice
WHERE date / 86400000 = 1524636334412 / 86400000
results in :-
As such you could change :-
String query = "SELECT * FROM " + TABLE_INVOICE + " WHERE " + INVOICE_DATE + " LIKE \'"+longDate+"\'";
to be
String query = "SELECT * FROM " + TABLE_INVOICE + " WHERE " + INVOICE_DATE + " / 86400000 = " + longDate + " / 86400000";

how to write where clause with rawquery

Hi, I have some problem to fetch data from sqlite database. Here i am fetching
data from select query but it is not responding. Please help me.
public ArrayList<String> getStudentsByClass(String stud_info) {
// Log.i("SKR", "GETTING STUDENTS by " +stud_class);
ArrayList<String> arrayList = new ArrayList<>();
Cursor cursor = liteDatabase.rawQuery("SELECT * FROM " + DATABASE_TABLE2 +
" WHERE ssg ='" + stud_info + "'", null);
if (cursor != null) {
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
arrayList.add(cursor.getString(cursor.getColumnIndex(KEY_STUDENT_NAME)));
cursor.moveToNext();
}
}
}
return arrayList;
}
Here is a raw query from a DBHelper Class that when called populates an ArrayList
/* Retrive ALL data from database table named "TABLE_INFO" */
public List<DatabaseModel> getDataFromDB(){
List<DatabaseModel> modelList = new ArrayList<>();
String query = "SELECT * FROM " + TABLE_INFO;
//String query = "SELECT * FROM " + TABLE_INFO + " WHERE " + Col_ID + " > 0 " + " ORDER BY " + Col_ID + " DESC ";
/* Notice the SPACES before AND after the words WHERE ORDER BY ASC or DESC most of all the condition " > 0 "*/
/* =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=*/
db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query,null);
if (cursor.moveToFirst()){
do {
DatabaseModel model = new DatabaseModel();
model.setID(cursor.getString(0));
model.setWebsite(cursor.getString(1));
model.setUsernane(cursor.getString(2));
model.setPassword(cursor.getString(3));
model.setQuestion(cursor.getString(4));
model.setAnswer(cursor.getString(5));
model.setNotes(cursor.getString(6));
modelList.add(model);
}while (cursor.moveToNext());
}
db.close();
return modelList;
}
using rawQuery You may include ?s in where clause in the query, which will be replaced by the values from selectionArgs. The values will be bound as Strings.
String selectQuery = "select * FROM settings where _id = ?";
String args[] = {"1"};
Cursor c = db.rawQuery(selectQuery, args);
if (c.moveToFirst()) {

Gridview data binding

I have a problem when when while loop repeats it iteration the already binded is replacing by new records but i want to bind all data by the iteration of while loop.
I am a new I have no idea how it can be.
while (i >= 0)
{
if (i != 0)
{
group_idd = group_ids[--i];
}
SqlConnection connection3 = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection_String"].ConnectionString);
using (connection3)
{
using (SqlCommand cmdd = new SqlCommand())
{
cmdd.CommandText = "SELECT [news_category],[id] FROM [news_profile] WHERE [user_id]='" + user_id + "' AND [group_id]='" + group_idd + "' AND [profile_id] IS NOT NULL";
cmdd.Connection = connection3;
connection3.Open();
GridView1.DataSource = cmdd.ExecuteReader();
GridView1.DataBind();
connection3.Close();
}
}
if (i == 0)
{
--i;
}
}
Create a small class
public class NewsProfile
{
public string NewsID { get; set; }
public string NewsCategory { get; set; }
}
Now in your code-behind, do this
List<NewsProfile> newsProfiles = new List<NewsProfile>();
// while loop here
SqlConnection connection3 = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection_String"].ConnectionString);
using (connection3)
{
using (SqlCommand cmdd = new SqlCommand())
{
cmdd.CommandText = "SELECT [news_category],[id] FROM [news_profile] WHERE [user_id]='" + user_id + "' AND [group_id]='" + group_idd + "' AND [profile_id] IS NOT NULL";
cmdd.Connection = connection3;
connection3.Open();
while (reader.Read())
{
NewsProfile np = new NewsProfile();
np.NewsCategory = reader.IsDBNull(0) ? "" : reader.GetString(0);
np.NewsID = reader.IsDBNull(1) ? "" : reader.GetString(1);
newsProfiles.Add(np);
}
}
}
//end while loop here
GridView1.DataSource = newsProfiles;
GridView1.DataBind();

Resources