Android SQLite specific table row deletion - java

I have some trouble removing specific users from my SQLite database on my Android device. I made a simple method to delete a table row where table.name equals first input and table.surname equals second input.
Here is my method:
void deleteUser(db_operations opt, String name, String surname) {
SQLiteDatabase sdb = opt.getWritableDatabase();
if(validate(name, surname) == true) {
name = name.replaceAll("\\s+",""); surname = surname.replaceAll("\\s+","");
try {
String DELETE_USER = "DELETE FROM " + tb_users.tb_name + " WHERE " + tb_users.name + "='" + name + "' AND " + tb_users.surname + "='" + surname + "'";
sdb.execSQL(DELETE_USER);
sdb.close();
System.out.println("Deletion SUCCESS!");
} catch (SQLException e) {
System.out.println("Deletion FAILED!");
}
}
}
If I execute a DELETE FROM myTableName statement, every user is removed from the table and from my ScrollView which is ok, but if I execute the above method to remove a specific user, output gives:
Deletion SUCCESS!
but my table still has the record. The record also remains in my ScrollView list (made with LinearLayouts). The list is built dynamically. I've already checked if the data is good or not before my SQLite execution starts and it looks ok. I can't figure out why my method doesn't work. Maybe I've missed something.

(Posted on behalf of the question author).
I got it working. I found out that my validation method was returning false output all the time (I made a typo in one of the conditions), that's why my method never got a chance to execute. Thanks for a reminder to use logs. Was able to track my typo.

Related

How to insert all of the selected jcheckbox values into database

I have been trying to insert all of the selected jcheckbox values into a MySQL database but could not find any source. I want to do a program where teachers can select all of the courses (course code) taken by student and store them into the database column. I have tried appending all of the checkbox values into one string variable (code is given below) but don't know how to get all of the courses individually and insert them into database (since courses appear as a string). I have no idea how to do so. However it is also possible to append jcheckbox in jtable and then select all the rows (which are necessary) to insert into the database.
Please help me with one of the ways stated above. Help would be appreciated. Thank you.
if (jCheckBox1.isSelected()) {
GetAllValues += jCheckBox1.getText() + " ";
}
if (jCheckBox2.isSelected()) {
GetAllValues += jCheckBox2.getText() + " ";
}
if (jCheckBox3.isSelected()) {
GetAllValues += jCheckBox3.getText() + " ";
}
if (jCheckBox4.isSelected()) {
GetAllValues += jCheckBox4.getText() + " ";
}

Retrieving a database value and assigning to a string value

I am making a app that incorporates login/register functionalities and I'm making a issue that I have been trying to solve.
When a user logins and the login is successful, I'd like to use the email that they signed in with to pass to the next activity using Intent (I checked that the email is in fact getting passed by displaying what is being passed through the intent) and then passing that email to a function in the Dbhelper that uses that email to look for the name of the person that signed in then displaying "Welcome (name of person)" in the current activity but I keep getting a null returned in the function which ultimately leads to the app crashing.
Here is where I'm calling the function in the activity where I want to display the name.
if(!session.loggedIn())
{
Logout();
}
else
{
Intent in = getIntent();
String email = in.getStringExtra("email");
Name.setText("Welcome " + db.findName(email));
}
And this is the function in my DbHelper.java where I'm looking for the name with a query and such.
public String findName(String user_email)
{
String query = "SELECT " + COLUMN_NAME + " FROM " + USER_TABLE + " WHERE " + COLUMN_EMAIL + " = " + "'" + user_email + "'";
SQLiteDatabase db = this.getWritableDatabase();
//reads for database
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
if(c.getCount() > 0) // if cursor is not empty
{
String n = c.getString(0);
return n;
}
else
{
return null;
}
}
As you can see, it's returning null. And yes there is entries in the database already. Also, I tried just passing the email to the function and returning what was passed and it still gave me an error.
Normally, to check for a value in a text column, you do not use the equal = sign, but rather WHERE Column LIKE '%text%'. Also, when saving to a database you should escape and "sanitize" strings. If you did this, then you should also be doing the same process when looking for them, else you won't find them.
I am telling you this since, even if you are sure there are entries in your table, the result of the query may be empty. You could just debug by printing the result of the c.getCount() call or something.

Spring JDBC Data Driven Update

I have a Spring application with a update API endpoint for a Postgres database. The user can submit information and updates will be reflected in the database. The user only submits what they have to update. For example consider the following object:
class Dog {
String name;
int age;
String breed;
// Attributes and getters/setters...
}
When the user submits a update request, they only send the information they wish to update, such as only name and breed. I have the following function that updates the database with information:
public void update(String name, int age, String breed, JdbcTemplate template) {
UpdateBuilder query = new UpdateBuilder();
query.from("DogTable");
boolean updated = false;
if (name != null) {
query.set("name" + " = '" + name + "'");
updated = true;
}
if (age != null) {
query.set("age" + " = '" + age + "'");
updated = true;
}
if (breed != null) {
query.set("breed" + " = '" + breed + "'");
updated = true;
}
// And so on...
if (updated) {
query.set("UpdatedTime" + " = '" + new Date() + "'");
}
query.where("someKey" + " = '" + someId + "'");
template.update(query.toString());
}
(The query.set() stuff is just a helper class that builds a query string)
As you can see, this gets messy with all the "is the name given, is the age given?" checks. That leads to my question: Is there a data driven approach to do this? What I would like to be able to do is:
myJdbcTemplate.update(ListOfObjectsToUpdate, "TableName");
Simply, the JDBC template would see what I have provided it, and would proceed to update the provided table with that information. Is this even possible? I realize that building queries using strings is bad, but PreparedStatements don't look much better in code (not to mention, they don't solve this issue).
You can use the COALESCE function for this purpose - add user value as well and existing value and if the user value is not null (intended update) it well be set as the new value.
Similar to this -
UPDATE "user" SET alternate_contact_name = COALESCE(<user value>, alternate_contact_name)
This is a MySQL query but COALESCE works same way in Postgresql
The user value will be set and new value if it is not null. When it is null and original value of column is not null, the original value if picked. If both are null then it doesn't matter.
WIth this you can simply pass all parameters and avoid building query in an untidy way.

Deleting from SQLite in Android

I have a SQLite DB with a table called "students". In the students table, there are 2 columns: "student_id" and "student_name".
I am trying to delete a row from an SQLite table using this code:
String TABLE_STUDENTS = "students";
String COLUMN_STUDENTNAME= "student_name";
public void deleteUser(String name) {
database.delete(TABLE_STUDENTS, COLUMN_STUDENTNAME + "=" + name, null);
}
However, when I try to delete the user "John" I get this error message from LogCat
12-19 16:28:47.132: E/SQLiteLog(14883): (1) no such column: John
I was trying to follow the example here: Deleting Row in SQLite in Android, but I could swear my syntax is the same.
Guessing I am doing something stupid, but anyone able to help? Thanks.
You may try:
database.delete(TABLE_STUDENTS,COLUMN_STUDENTNAME +" = ?", new String[] { name });
What you are doing is sending the equivalent statement DELETE FROM students WHERE student_name=John, which is why it is looking for a column called John. You need to use the third parameter of the method to provide the argument, so:
final String[] deleteConditions = new String[]{ name };
database.delete(TABLE_STUDENTS, COLUMN_STUDENTNAME + "=?", deleteConditions);
Note that you can delete multiple rows by adding more entries to the array deleteConditions.
That works, although I would recommend
db.delete(TABLE, "column_name=?", new String[] { String.valueOf(custname) });
or use
String query = "DELETE FROM " +TABLE_NAME+ " WHERE " + COLUM_NAME+ " = " + "'"+VALUE +"'" ;
db.execSQL(query);

Using one query in another in JDBC programming

I understand how to do this on paper in SQL, but am having trouble implementing this in Java (this is the first time I am actually programming JDBC stuff)
For example, say my database consists of:
movie(code, title, publisher)
customer(custno, name)
borrowed(custno, code)
And I want to find the name of customers who borrowed every movie by pubisher ABC
string no_of_ABC_movies = "SELECT COUNT(publisher), publisher FROM movie, WHERE movie.publisher = 'ABC'";
string no_of_cust_ABC_movies = "SELECT COUNT(name), name FROM customer, borrowed, movie, WHERE customer.custno = borrowed.custno AND borrowed.code = movie.code AND movie.publisher = 'ABC'";
String query = "SELECT name" +
" name FROM customer, borrowed, movie" +
" WHERE customer.custno = borrowed.custno AND" +
" borrowed.code = movie.code AND" +
" movie.publisher = 'ABC' AND" + " "
no_of_cust_ABC_movies + " = " + no_of_ABC_movies;
This isn't the exact database I am working with, but query will work and print out the names of people who borrowed movies from ABC without the last line, but says I have an error in SQL syntax with the last line so I guess I don't know how to use one query within another.
It depends on your DBMS, but every SQL variant I've seen requires parens around subqueries.
Try something like:
...
" movie.publisher = 'ABC' AND ("
no_of_cust_ABC_movies + ") = (" + no_of_ABC_movies + ")";
You have problem with double name field without being separated by a comma in your query.
If your code is exactly as listed above, you have compilation error just above the last line-missing + to concatenate strings.
If that's a typo below is my suggestion.
Remove duplicate select (use only one name) or
Separate names by a comma ( I don't see a point of selecting name twice though)
And your last line is wrong.. you can not compare two select queries that way.. Just add the required where clauses.
(You should read database joins first, and then solve your problem)
I like to get my queries working in the query browser or workbench, then copy them over to Java. It keeps it to one new thing at a time...
You're query actually starts with
SELECT name name FROM customer ...
The name column is duplicated - maybe that the problem.

Categories

Resources