Android Insert Statement - java

I have create an android application where in users can add, update, and delete stuffs from the database
In my DataSource java file i have this code:
public void addWebsite(String sitename, String username, String password) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_URL, sitename);
values.put(MySQLiteHelper.COLUMN_USERNAME, username);
values.put(MySQLiteHelper.COLUMN_PASSWORD, password);
database.insert(MySQLiteHelper.TABLE_URL, null,values);
}
the above code makes the insert statement.
public void updateWebsite(WebsiteRecords website){
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_URL, website.getSitename());
values.put(MySQLiteHelper.COLUMN_USERNAME, website.getUsername());
values.put(MySQLiteHelper.COLUMN_PASSWORD, website.getPassword());
database.update(MySQLiteHelper.TABLE_URL, values, MySQLiteHelper.COLUMN_ID + " = " + website.getId(), null);
}
the above code displays an update statement
public void deleteWebsite(WebsiteRecords website) {
database.delete(MySQLiteHelper.TABLE_URL, MySQLiteHelper.COLUMN_ID + " = " + website.getId(), null);
}
and lastly, the above code is for the delete statement.
My problem is, I get this username from my login, and from that I want to add, update and delete stuffs which has the username i got from my login screen. I was thinking of making
Cursor mCursor = database.rawQuery("INSERT INTO " + TABLE_URL + " VALUES('" + sitename + "', '" + username + "', '" + password + "') " WHERE loginname=?", new String [] {loginname});
or anything like that but I am scared that it won't work. Same goes with the update and delete. It will only add, update, delete, view files which has a loginname of for instance "iamcoolin3d".
Anyone can help me with this?

The line:
Cursor mCursor = database.rawQuery("INSERT INTO " + TABLE_URL + " VALUES('" + sitename + "', '" + username + "', '" + password + "') " WHERE loginname=?", new String [] {loginname});
Should be:
Cursor mCursor = database.rawQuery("INSERT INTO " + TABLE_URL + " VALUES('" + sitename + "', '" + username + "', '" + password + "') WHERE loginname=?", new String [] {loginname});
there is an extra " before WHERE

There is a problem with your last line, you must put WHERE in the String, otherwise it won't work.

Related

inserting to database using java gui

I am trying to insert data from my netbeans to mysql workbench. there is no problem with the query but when I run the program a message box appear "Unknown column 'empJob' in 'field list '" . What seems to be the problem?
and just to Know i tried this on another table and it works just fine! but in this one it doesn't work!
int id, Salary;
String name, Address, Jop;
id = Integer.parseInt(tNo.getText());
name = tName.getText();
Address = tAddress.getText();
Jop = tJop.getText();
Salary = Integer.parseInt(tNo.getText());
String sql = "insert into employee(empid,empName, empAddress,empJob,empSalary) values('" + id + "','" + name + "' , '" + Address + "','" + Jop + "','" + Salary + "')";
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
int x = st.executeUpdate(sql);
if (x > 0) {
JOptionPane.showMessageDialog(prev, x + "rows effected");
} else {
JOptionPane.showMessageDialog(prev, "insert failed");
}
Do you have a typo? You write empJob -> but your variable is called Jop. So maybe it should be empJop.
String sql = "insert into employee(empid,empName, empAddress,empJop,empSalary) values('" + id + "','" + name + "' , '" + Address + "','" + Jop + "','" + Salary + "')";

Error when trying to update an existing row in sqlite database in Android java?

I'm trying to update the database with the value in edit text. But I get an error in the logger: "*** Process: com.example.coursework2, PID: 12430
android.database.sqlite.SQLiteException: no such column: Wordc (code 1 SQLITE_ERROR): , while compiling: UPDATE Phrases_table SET word = Word WHERE word = Wordc
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
Wordc is the word stored in the database and "Word" is the value im trying to update the database with. I'm new to this, please help.**
// database class, I have only only 1 column which is COL_2
public void updateName(String newName,String oldName) { // issue is here
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE " + TABLE_NAME + " SET " + COL_2 + " = " + newName + " WHERE " + COL_2 + " = " + oldName;
db.execSQL(query);
/*Edit class, where when I click on the save button, I get the value from the radio button and expect to update the database with the value in the edit text */
buttonSave.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = listView.getCheckedItemPosition();
if (pos > -1) {
val = list.get(pos).toString(); //getting value from the radio button which is stored in the database
String newWord= edit.getText().toString(); //getting text from edit text
myDb.updateName( newWord,val );
}
The string values should be enclosed inside single quotes:
public void updateName(String newName,String oldName) { // issue is here
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE " + TABLE_NAME + " SET " + COL_2 + " = '" + newName + "' WHERE " + COL_2 + " = '" + oldName + "'";
db.execSQL(query);
}
But you should use the recommended and safer method update() with ContentValuesand ? placholders:
public void updateName(String newName, String oldName) { // issue is here
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COL_2, newName);
db.update(TABLE_NAME, cv, COL_2 + "= ?", new String[] {oldName});
db.close();
}
This way you don't have to worry about adding the single quotes or the risk of sql injection.
You are passing the native query directly, so you need to use quotes on string values:
String query = "UPDATE " + TABLE_NAME + " SET " + COL_2 + " = \"" + newName + "\" WHERE " + COL_2 + " = \"" + oldName + "\"";
db.execSQL(query);
This will generate the query:
UPDATE Phrases_table SET word = "Word" WHERE word = "Wordc"

Insert of rows in android database not working

I have a serious problem with my android studio's app!
I have created a db with two table. The problem happen when I insert the data. Infact, when I insert the data in the form, the previous one are deleted!
------------For example-------------------
First insertion:
Name --> a
Password --> a
Second insertion:
Name --> b
Password --> b
But the first insertion is canceled!
I hope that anyone help me... I put some code to understand my problem:
DatabaseOperation.java
private static final String CREATETABLE_QUERY_USER =
"CREATE TABLE " + UserContact.DatabaseInfo.TABLE_USER + " ( "
+ UserContact.UserInfo.ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ UserContact.UserInfo.USERNAME + " TEXT NOT NULL, "
+ UserContact.UserInfo.PASSWORD + " TEXT NOT NULL, "
+ UserContact.UserInfo.EMAIL + " TEXT NOT NULL, "
+ UserContact.UserInfo.PHONE_NUMBER + " TEXT NOT NULL "
+ " );"
;
private static final String CREATETABLE_QUERY_PASSWORD =
"CREATE TABLE " + UserContact.DatabaseInfo.TABLE_PASS + " ( "
+ UserContact.PasswordTable.ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ UserContact.PasswordTable.NAME + " TEXT NOT NULL, "
+ UserContact.PasswordTable.POSTERPASSWORD + " INTEGER NOT NULL, "
+ UserContact.PasswordTable.DESCRIPTION + " TEXT NOT NULL, "
+ UserContact.PasswordTable.PASSWORD + " TEXT NOT NULL "
//+ " FOREIGN KEY(" + UserContact.PasswordTable.ID + ") REFERENCES " + UserContact.DatabaseInfo.TABLE_USER + "(" + UserContact.UserInfo.ID +")
+ " );"
;
public void addUser(SQLiteDatabase db, String username, String password, String email, String phone){
ContentValues contentValues = new ContentValues();
contentValues.clear();
contentValues.put(UserContact.UserInfo.USERNAME, username);
contentValues.put(UserContact.UserInfo.PASSWORD, password);
contentValues.put(UserContact.UserInfo.EMAIL, email);
contentValues.put(UserContact.UserInfo.PHONE_NUMBER, phone);
db.insert(UserContact.DatabaseInfo.TABLE_USER, null, contentValues);
}
public void addPassword(SQLiteDatabase db, String name, String note, String password, int posterpassword){
ContentValues contentValues = new ContentValues();
contentValues.clear();
if(password.length() > 0){
contentValues.put(UserContact.PasswordTable.POSTERPASSWORD, posterpassword);
contentValues.put(UserContact.PasswordTable.NAME, name);
contentValues.put(UserContact.PasswordTable.DESCRIPTION, note);
contentValues.put(UserContact.PasswordTable.PASSWORD, password);
db.insert(UserContact.DatabaseInfo.TABLE_PASS, null, contentValues);
Log.e("DATABASE OPERATION", " INSERT PASSWORD successfull in " + UserContact.DatabaseInfo.TABLE_PASS + "...");
}
}
NewContact.java
String name = usernameEditText.getText().toString();
String password = passwordEditText.getText().toString();
String mail = emailEditText.getText().toString();
String phone = phoneEditText.getText().toString();
//Add user to database
String dbFile = getDatabasePath(UserContact.DatabaseInfo.DB_NAME).getPath();
databaseOperations = new DatabaseOperations(context);
sqLiteDatabase = SQLiteDatabase.openOrCreateDatabase(dbFile, UserContact.DatabaseInfo.password, null);
sqLiteDatabase = databaseOperations.getWritableDatabase(UserContact.DatabaseInfo.password);
databaseOperations.addUser(sqLiteDatabase, name, password, mail, phone);
Log.e("New Contact: " , "Success! -> username: " + name + ", password: " + password);
//End to add user----------------------------------
//After registration, return to authentication page
Intent intent_authenticationPage = new Intent(getApplicationContext(), AuthenticationPage.class);
startActivity(intent_authenticationPage);
I am not getting your database structure but anyways try changing the CREATE TABLE syntax from
CREATE TABLE <table_name>(...)
to
CREATE TABLE IF NOT EXISTS <table_name>(...)

Android filter sqlite results for listview

Hi im having problems with the syntax for the query string for filtering results for a listview showing sqlite results on Android.
public Cursor searchByInputText(String inputText) throws SQLException {
String query = "SELECT _id as _id," +" title" + " from " + TABLE_NAME + " where " + "title" + " LIKE '" + inputText + "';";
//String query = "SELECT _id as _id," +" title" + " from " + TABLE_NAME + " where " + "title" + " LIKE '" + inputText + "';";
//String query = "SELECT _id from " + TABLE_NAME + " WHERE title="+inputText;
Cursor mCursor = database.rawQuery("SELECT _id as _id, title from "+TABLE_NAME +" where title like " + inputText,null);
if (mCursor != null) {
mCursor.moveToFirst();
System.out.println(query);
}
return mCursor;
}
I have tried so many solutions, but none seem to work for me, any sugggestions would be great.. Thanks
When you are using String type in where clause, it should be in single quotes.
where title like '%" + inputText +"'"

General error when trying to insert data into database

I am trying to insert data into a database and once again I cant seem to get to the bottom as to why I am getting a general error.
Any advice as to how to overcome this problem.
Class.forName(driverName);
connection = DriverManager.getConnection(SourceURL, user, password);
int rowAdded;
Object typeId = comboKeys.getSelectedItem();
String typeIdString = typeId.toString();
int typeIdInt = Integer.parseInt(typeIdString);
String animalIDString = txtAnimalID.getText();
int animalID = Integer.parseInt(animalIDString);
System.out.println(animalID);
String name = txtName.getText();
Statement statement = connection.createStatement();
String queryString = "INSERT INTO Animal (animalID, name, typeIDForeign) VALUES (" + animalID + ", '" + name + "', '" + typeIdInt + "')";
rowAdded = statement.executeUpdate(queryString);
connection.close();
Kind regards
Arian
Error
You have typeIdInt as Integer, however in the sql query, you are stating it as string (because you surround it with single quotes)
Solution
String queryString = "INSERT INTO Animal (animalID, name, typeIDForeign) VALUES (" + animalID + ", '" + name + "', '" + typeIdInt + "')";
should be :
String queryString = "INSERT INTO Animal (animalID, name, typeIDForeign) VALUES (" + animalID + ", '" + name + "', " + typeIdInt + ")";
Look at " + typeIdInt + ". You have '" + typeIdInt + "'
Good Luck!!!

Categories

Resources