Incorrect and duplicated results from a sqlite fts3 unionQuery - sqlite

I'm getting results from my rawQuery that duplicate and follow an OR logic as opposed to an AND logic i.e. I will get all the entries that contain "tuxedo" as well as all the entries that contain "hotel" when I only want the ones that contain both.
This is my method:
public ArrayList<Integer> getAdvancedResultIDList(String[] search)
{
ArrayList<String> queryList = new ArrayList<String>();
ArrayList<Integer> resultsList = new ArrayList<Integer>();
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
this.mDB = GamesList.mDBHelper.getDatabase();
Cursor searchCursor = null;
try
{
//TODO:
// for each string in the search array search the whole of searchable table. Check that the results are only of the values that
// contain all the search strings, and add the id of that row to the results ArrayList
for(int i = 0; i < search.length; i++)
{
String query;
String s = '"' + search[i] + '"';
query = "SELECT " + KEY_ID + " FROM "+ SEARCHABLE_TABLE + " WHERE " + SEARCHABLE_TABLE + " MATCH " + s;
queryList.add(query);
}
String[] queryArray = queryList.toArray(new String[queryList.size()]);
String unionQuery = builder.buildUnionQuery(queryArray, KEY_ID + " ASC", null);
searchCursor = this.mDB.rawQuery(unionQuery, null);
int colId = searchCursor.getColumnIndex(KEY_ID);
String resultID;
for(searchCursor.moveToFirst(); !searchCursor.isAfterLast();searchCursor.moveToNext())
{
resultID = searchCursor.getString(colId);
Integer Id = Integer.parseInt(searchCursor.getString(colId));
resultsList.add(Id);
}
searchCursor.close();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
this.mDB.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
return resultsList;
}
Thanks in advance and Happy New Year!

The documentation explains how to use multiple search terms:
SELECT id FROM searchTable WHERE searchTable MATCH 'tuxedo hotel'

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

SQLite exception: Database is locked

I have looked into all the questions on the "database is locked" exception but none solve my problem. I have a static function in DBActions class that inserts a record in DB as follows:
public static class DBActions
{
// save col, value pairs in DB table
public static int SaveInDB(string table, string[] cols, object[] vals)
{
int resultID = 0;
string query = $"insert into {table} (";
for (int i = 0; i < cols.Length - 1; i++)
{ // leave the last column coz comma does not follow it
query += cols[i] + ", ";
}
query += cols[cols.Length - 1] + ") values (";
for (int i = 0; i < cols.Length - 1; i++)
{
query += $"'{vals[i]}', ";
}
query += $"'{vals[vals.Length - 1]}')";
//MessageBox.Show(query);
using (SQLiteConnection con = new SQLiteConnection(Global.ConnectionString))
{
using (SQLiteCommand cmd = new SQLiteCommand(con))
{
try
{
con.Open();
using (SQLiteTransaction trans = con.BeginTransaction())
{
cmd.CommandText = query;
cmd.ExecuteNonQuery();
resultID = (int)con.LastInsertRowId;
trans.Commit(); // raises the exception
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
con.Close();
cmd.Dispose();
}
}
}
return resultID;
}
}
and I am calling this static function whenever I need to save some record in any table like this:
Global.StartTime = GetCurrentTimeStamp();
string[] cols = { "SampleID", "OperatorID", "StartTimeStamp"};
object[] vals = { SampleID, CurrentUser, Global.StartTime};
Global.ExpID = DBActions.SaveInDB("ExperimentSettings", cols, vals);
When I call it the very first time, it throws the "database is locked" exception. For all others, it executes fine. What could be the possible cause of this? I think all my DB objects are properly being disposed off due to the using statements.

how to refer to a non-declared variables in setResultConverter

I'd like to re-use a dialog class for data manipulation. The data will be retrieved from database. It depends on which table the class retrieve the data from, the size of the table columns is not fixed, so I can't declare column variables. After users update data, I would like to convert the input data using setResultConverter but do not know how to refer to the variable, since the program generates TextFields dynamically. Please help. Here is the the code.
public class AddDialog {
private Dialog<DBtable> dialog = new Dialog<DBtable>();
private ButtonType saveBtn;
//database variables
private Connection connect; // = null;
private String dbTblName;
//gridpane content variables
private GridPane contentPane = new GridPane();
private HashMap<String, TextField> fieldMap =
new HashMap<String, TextField>();
private ArrayList<String> dataList = new ArrayList<String>();
public AddDialog (String title, String header, String dbTable) {
this.dbTblName = dbTable;
dialog.setTitle(title);
dialog.setHeaderText(header);
saveBtn = new ButtonType("Save", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(saveBtn,
ButtonType.CANCEL);
dialog.getDialogPane().setContent(getLayout(dbTable));
Optional<DBtable> result = dialog.showAndWait();
result.ifPresent(data -> {
System.out.println(" data="+data+" 0="+data.getID()+
" 1="+data.getField1());
});
} // constructor ends
public GridPane getLayout(String dbTable) {
String sql = "select column_name, description ";
sql += "from syscolumn_description ";
sql += "where table_name = \'" + dbTable + "\'";
String fieldLabel, fieldCol;
ResultSet ds = null;
// retrieve meta data from database
connect = DBConnect.getConnect(connect);
try {
Statement labelStmnt = connect.createStatement();
ds = labelStmnt.executeQuery(sql);
int row = 0;
while (ds.next()) {
row += 2;
//label....column=0 row=row+2;
fieldLabel = ds.getString("DESCRIPTION");
contentPane.add(new Text(fieldLabel), 0, row);
//textField...column=1 row=row+2;
contentPane.add(new TextField(), 1, row);
fieldCol = ds.getString("COLUMN_NAME");
fieldMap.put(fieldCol, new TextField());
} // while result set loop ends
} catch (Exception e) {
e.printStackTrace();
} finally {
try {if(ds != null) ds.close();} catch (Exception e) {};
}
// convert result
dialog.setResultConverter(dialogButton -> {
if (dialogButton == saveBtn) {
int i=0;
for (Map.Entry<String, TextField> e : fieldMap.entrySet()) {
dataList.add(e.getValue().getText());
i++;
System.out.println("col="+e.getKey()+
" data="+e.getValue().getText());
} // map loop end
return new DBtable(dataList, i);
}
return null;
});
return contentPane;
} //getLayout ends
} // AddDialog ends

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.

SQLite keep expanding

I'm new to the blackberry development and to this site. right now, i'm working on an app that retrieve data from a json service. In my app I should parse the data into a database and save it in four tables. I already parsed the data and I was successful able to create the database and add the first and the second tables.
The problem that I'm facing right now is, the second table in my data base keep expanding. I checked the database in the sql browser and I discovered that everytime I click on the app icon it adds the 700 rows to the table again.(ex. 700 becomes 1400) .
(only to the second table, the first table works so fine).
Thank you in advance
This is my code:
public void parseJSONResponceInBB(String jsonInStrFormat)
{
try {
JSONObject json = newJSONObject(jsonInStrFormat);
JSONArray jArray = json.getJSONArray("tables");
for (inti = 0; i < jArray.length(); i++) {
//Iterate through json array
JSONObject j = jArray.getJSONObject(i);
if (j.has("Managers")) {
add(new LabelField("Managers has been added to the database"));
JSONArray j2 = j.getJSONArray("Managers");
for (intk = 0; k < j2.length(); ++k) {
JSONObject MangersDetails = j2.getJSONObject(k);
if (MangersDetails.has("fName")) {
try {
URI myURI =
URI.create
("file:///SDCard/Databases/SQLite_Guide/"
+ "MyTestDatabase.db");
d = DatabaseFactory.openOrCreate(myURI);
Statement st =
d.createStatement
("CREATE TABLE Managers ( "
+ "fName TEXT, " +
"lName TEXT, " + "ID TEXT," + "Type TEXT )");
st.prepare();
st.execute();
st.close();
d.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
try {
URI myURI =
URI.create
("file:///SDCard/Databases/SQLite_Guide/"
+ "MyTestDatabase.db");
d = DatabaseFactory.open(myURI);
Statement st =
d.createStatement
("INSERT INTO Managers(fName, lName, ID, Type) "
+ "VALUES (?,?,?,?)");
st.prepare();
for (intx = 0; x < j2.length(); x++) {
JSONObject F = j2.getJSONObject(x);
//add(new LabelField ("f"));
st.bind(1, F.getString("fName"));
st.bind(2, F.getString("lName"));
st.bind(3, F.getString("ID"));
st.bind(4, F.getString("Type"));
st.execute();
st.reset();
}
d.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
}
}
}
catch(JSONException e) {
e.printStackTrace();
}
}
//Owners method
public voidparseJSONResponceInBB1(String jsonInStrFormat)
{
try {
JSONObject json = newJSONObject(jsonInStrFormat);
JSONArray jArray = json.getJSONArray("tables");
for (inti = 0; i < jArray.length(); i++) {
//Iterate through json array
JSONObject j = jArray.getJSONObject(i);
if (j.has("Owners")) {
add(new LabelField("Owners has been added to the database"));
JSONArray j2 = j.getJSONArray("Owners");
for (intk = 0; k < j2.length(); ++k) {
JSONObject OwnersDetails = j2.getJSONObject(k);
if (OwnersDetails.has("fName")) {
try {
Statement st =
d.createStatement
("CREATE TABLE Owners ( "
+ "fName TEXT, " +
"lName TEXT, " + "ID TEXT," + "Type TEXT )");
st.prepare();
st.execute();
st.close();
d.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
try {
Statement st =
d.createStatement
("INSERT INTO Owners(fName, lName, ID, Type) "
+ "VALUES (?,?,?,?)");
st.prepare();
for (intx = 0; x < j2.length(); x++) {
JSONObject F = j2.getJSONObject(x);
//add(new LabelField ("f"));
st.bind(1, F.getString("fName"));
st.bind(2, F.getString("lName"));
st.bind(3, F.getString("ID"));
st.bind(4, F.getString("Type"));
st.execute();
st.reset();
}
d.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
}
}
}
catch(JSONException e) {
e.printStackTrace();
}
}
It depends on what your goals are here. If you want to replace the data in the database each time the json query runs, you should add a sqlite command to remove all the existing rows with the newly fetched ones coming in via JSON.
If you just want to keep certain types of records unique, you should add an index to the sqlite table. The 'ID' column is a likely candidate for this. You'll have to do some experiments to make sure a conflict is handled correctly - it may abort the entire transaction. "INSERT OR REPLACE" is useful in that situation.

Resources