Checking before insert - java

I would like to check my first field and the second (CodeA, TitreA) and stop duplicates.
I don't know what to do.
public boolean insertAlbum (Album alb)
{
boolean ok = ConnexionMySQL.getInstance().actionQuery(
"Insert into album (CodeA, TitreA, SortieA, IdentC) values ('" +
alb.getCodeA() + "','" +
alb.getTitreA() + "'," +
alb.getSortieASQL() + "," +
alb.getChanteurAlb().getIdentC() + ")");
return ok;
}

Your database table should enforce uniqueness of that column combination. Add this to your database:
alter table album add constraint unique_code_titre unique (codea, titrea);
Then, if you try inserting the same combination, it will show you an error, and won't insert the new row.

Related

Issue deleting row from SQL Table

I'm trying to remove a row from an SQL table using this code below. However, whenever I call this method I get this following error:
android.database.sqlite.SQLiteException: no such column: Plumber (code 1): , while compiling: DELETE FROM service WHERE name = Plumber
public boolean deleteService(String name){
SQLiteDatabase db = this.getWritableDatabase();
boolean result = false;
String query = "SELECT * FROM "
+ TABLE_SERVICE
+ " WHERE "
+ COLUMN_NAME
+ " = \""
+ name
+ "\""
;
Cursor cursor = db.rawQuery(query, null);
if(cursor.moveToFirst()){
String nameStr = cursor.getString(0);
db.delete(TABLE_SERVICE, COLUMN_NAME + " = " + nameStr, null);
cursor.close();
result = true;
}
db.close();
return result;
}
This is my table
public void onCreate(SQLiteDatabase db){
String CREATE_USERS_TABLE = "CREATE TABLE " +
TABLE_SERVICE + "("
+
COLUMN_NAME + " TEXT," +
COLUMN_RATE + " TEXT," +
COLUMN_CATEGORY + " TEXT," + COLUMN_SUBCATEGORY + " TEXT)";
db.execSQL(CREATE_USERS_TABLE);
}
First you're fetching all the rows that in COLUMN_NAME have the value name.
Next you want to delete the 1st of these rows (maybe it's the only one?) because nameStr gets the value of the 1st column which is COLUMN_NAME.
Why are you doing this?
Just execute this statement:
int number = db.delete(TABLE_SERVICE, COLUMN_NAME + " = '" + name + "'", null);
if number gets the value 0 then no rows were deleted, else it gets the number of deleted rows.
delete deletes rows not columns.
If you want to get rid of a column, you need to drop it. The SQL syntax is:
alter table table_service drop column <column_name>;
I don't know how to express this in java with the methods that you are using.
Ensure that your SQL syntax is correct, and that "Plumber" is a string with double quotes. By my experience, these errors are usually caused by an incorrect column or name.
Use this format:
DELETE FROM table_name WHERE condition(s)
SQLite browser can also help you visualize your database.

Inserting Content Values in multiple tables in Sqlite Android Application

I am brand new to multiple tables in an SQLite database and am trying to find out what the best practices are for inserting values into multiple tables. My main question is do I need to Create another ContentValues object for inserting the values into a second table? I am really stumped on how to perform the insert(). Here is what I am trying so far.
Here are the two tables and schema
/* Creating a common attributes table here. */
private static final String CREATE_COMMON_ATTRIBUTES_TABLE = "create table "
+ COMMON_ATTRIBUTES_TABLE + "(" + DBColCons.UID_COMMON_ATTRIBUTES + " integer" +
" primary key autoincrement, " + DBColCons.GPS_POINT+ " integer not null, "
+ DBColCons.EXISTING_GRADE_GPS_POINT+ " integer not null, "
+ DBColCons.COVER+ " real not null, "+ DBColCons.NOTES+ " text, "
+ DBColCons.DATE+ " text)";
/* Creating a weld table here */
private static final String CREATE_WELD_TABLE = " create table " +WELD_TABLE+ "("
+ DBColCons.UID_WELD + " integer primary key, " + DBColCons.WELD_TYPE +
" text, " + DBColCons.WELD_ID + " text, " + DBColCons.DOWNSTREAM_JOINT +
" text, " + DBColCons.UPSTREAM_JOINT + " text, " + DBColCons.HEAT_AHEAD +
" text, " + DBColCons.LENGTH_AHEAD + " real, " + DBColCons.WALL_CHANGE +
" text, " + DBColCons.WELD_WALL_THICKNESS + " text, "
+ DBColCons.WELDER_INITIALS + " text, foreign key("+DBColCons.WELD_ID+") references" +
"("+DBColCons.GPS_POINT+"))";
Here is the method I am wanting to use for the insert() with some class getters() for the Weld class, which I am passing in as a parameter.
public boolean insertWeld(Weld weld) {
/* Get a writable copy of the database */
SQLiteDatabase db = this.getWritableDatabase();
/* Content values to insert with Weld class setters */
ContentValues contentValuesWeld = new ContentValues();
try {
contentValuesWeld.put(DBColCons.GPS_POINT, weld.getGpsPoint());
contentValuesWeld.put(DBColCons.WELD_TYPE, weld.getWeldType());
contentValuesWeld.put(DBColCons.WELD_ID, weld.getWeldId());
contentValuesWeld.put(DBColCons.DOWNSTREAM_JOINT, weld.getDownstreamJoint());
contentValuesWeld.put(DBColCons.UPSTREAM_JOINT, weld.getUpstreamJoint());
contentValuesWeld.put(DBColCons.HEAT_AHEAD, weld.getHeatAhead());
contentValuesWeld.put(DBColCons.LENGTH_AHEAD, weld.getLengthAhead());
contentValuesWeld.put(DBColCons.EXISTING_GRADE_GPS_POINT, weld.getExistingGradePoint());
contentValuesWeld.put(DBColCons.COVER, weld.getCover());
contentValuesWeld.put(DBColCons.WALL_CHANGE, weld.getWallChange());
contentValuesWeld.put(DBColCons.WELD_WALL_THICKNESS, weld.getWeldWallThickness());
contentValuesWeld.put(DBColCons.WELDER_INITIALS, weld.getWelderInitials());
contentValuesWeld.put(DBColCons.NOTES, weld.getNotes());
/* adding the date in here to the row. */
contentValuesWeld.put(DBColCons.DATE, String.valueOf(mStrDate));
/* Inserting into the weld table */
db.insertWithOnConflict(WELD_TABLE, DBColCons.WELDER_INITIALS, contentValuesWeld,
SQLiteDatabase.CONFLICT_NONE);
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
The values for DBColCons.GPS_POINT,DBColCons.EXISTING_GRADE_GPS_POINT,DBColCons.GPS_COVER and DBColCons.NOTES are what I want to insert into the Common_Attributes_Table. This is where I am really confused. Do I need to create a separate ContentValues object for those specific values and insert them into the desired table with a separate db.insert() method along with the one I am already using with the insert on the WELD_TABLE?
Help I am lost in this train wreck. Ha.
Thank you all.
You need to call insert() (or insertWithConflict()) for each table you are inserting values into. Unless the values are the same, this implies you will need another ContentValues per table.
If you intend for these inserts to be committed as a single atomic operation, consider using a transaction.
SQLiteDatabase db = ...;
db.beginTransaction();
try {
// do your inserts/etc. here
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}

Android: Delete all sqlite rows NOT IN top 5

I have a database for my leaderboard. Currently, I insert all scores into my leaderboard, and select the 5 highest scores to show on my app. I think it would take up too much room to never delete the other scores, so I would like to delete them. How can I do this?
Here's how I select the top 5 scores, ranked first by score and second by time if score is equal:
public Cursor gethmLeaderboard(SQLiteDatabase db){
String[] columns = {TableInfo.LB_RANK, TableInfo.LB_SCORE, TableInfo.LB_TIME};
Cursor c = db.query(TableInfo.TABLE_HM, null, null, null, null, null, TableInfo.LB_SCORE + " DESC, " + TableInfo.LB_TIME + " ASC", "5");
return c;
}
Here's how I create my table:
public String CREATE_HMQUERY = "CREATE TABLE " + TableInfo.TABLE_HM + "("
+ TableInfo.LB_RANK + " INTEGER PRIMARY KEY AUTOINCREMENT DEFAULT 1 ," + TableInfo.LB_SCORE +
" INT,"+ TableInfo.LB_TIME + " VARCHAR );";
I want to delete all rows NOT IN that query. How can I do that?
Edit:
I tried this query:
public String DEL_ALLBUTES = "DELETE FROM " +
TableInfo.TABLE_HM + " WHERE " +
TableInfo.LB_RANK + " NOT IN (SELECT " +
TableInfo.LB_RANK + " FROM " +
TableInfo.TABLE_HM + " ORDER BY " +
TableInfo.LB_SCORE + " DESC, " +
TableInfo.LB_TIME + " ASC LIMIT 5);";
In this format:
db.rawQuery(DEL_ALLBUTES, null);
But when I check the database there are still tons of rows so it doesn't work.
Your table needs to have some unique ID. Use that to identify the rows you want to keep:
DELETE FROM ES
WHERE ID NOT IN (SELECT ID
FROM ES
ORDER BY Score DESC, Time ASC
LIMIT 5);
You can create temp table insert top 5 score into temp table and delete all table then insert temp table into main table.
CREATE TEMP TABLE TempES AS SELECT
ID
FROM
ES
ORDER BY
Score DESC,
Time ASC
LIMIT 5;
DELETE
FROM
ES;
INSERT INTO ES SELECT
*
FROM
TempES;
DROP TABLE TempES;

Raw Query in Android SQLite - INSERT OR IGNORE

I'm having an issue inputting information into a Sqlite database on the app I'm creating. I was using the help of the Cursor before. I am used to MySQL although clearly not 'used to' that well.
I am trying to add to the database from a file. I had this working before but it would be added with the Cursor. I was then told that in order to make it so I could add new information to the file and have the app ONLY add the new information into the database I should use INSERT OR IGNORE.
Is this the correct syntax? I currently am not having any information inserted for whatever reason...
ourDatabase.rawQuery("INSERT OR IGNORE INTO " + DATABASE_TABLE + " ("+KEY_CLASS+",
" + KEY_QUESTION+ ") VALUES ('" + qclass + "', '" + question + "');", null);
This is my database:
"CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_CLASS + " TEXT NOT NULL, " +
KEY_QUESTION + " TEXT NOT NULL UNIQUE);
Thanks for the help in advance!
Your query seems right but try the one below anyway
ContentValues insertValues = new ContentValues();
insertValues.put(KEY_CLASS, qclass);
insertValues.put(KEY_QUESTION, question);
yourDbName.insertWithOnConflict(DATABASE_TABLE, null, insertValues, SQLiteDatabase.CONFLICT_IGNORE);
KEY_QUESTION + " TEXT NOT NULL UNIQUE);";

MySQL INSERT with duplicate support

I'm trying to use a MySQL database to save player information, but whenever there is a duplicate it will load (or save?) every player from the same player column.
Here's what I'm working with:
public boolean saveGame(String playerName, String playerPass) {
String player = "'" + playerName + "', '" + playerPass + "'";
String player2 = "`password` = '" + playerPass + "'";
String playerData = "'" + playerName + "', 'testtttt'";
String playerData2 = "`test` = 'testtttt'";
Server.getConnectionPool().executeUpdate("INSERT INTO player (username, password) VALUES (" + player + ") ON duplicate KEY UPDATE " + player2);
Server.getConnectionPool().executeUpdate("INSERT INTO playerdata (username, test) VALUES (" + playerData + ") ON duplicate KEY UPDATE " + playerData2);
return true;
}
public int loadGame(String name, String pass) {
ResultSet res = Server.getConnectionPool().executeQuery("SELECT * FROM player, playerdata WHERE player.username = '" + name + "'");
try {
name = res.getString("username");
if (!pass.equalsIgnoreCase(res.getString("password"))) {
return 3;
}
} catch (Exception e) {
e.printStackTrace();
}
return 1;
}
Here are the schemas (I removed the data from the example as it's not really needed, it doesn't load/save properly regardless):
Player:
image http://puu.sh/Alit.png
Playerdata:
image http://puu.sh/Aljr.png
I'm aware they'll be the same because I'm using the same string for the test field, but even if I do random ones or custom edit it in PHPMyAdmin it'll still save and then load from the same column. I think that it's saving because it seems to load the player properly, it's just not updating the proper column, which I don't know how to do. Inside the playerdata table all of the data for every single person is the same, and I don't know what's causing it, any ideas?
I have fixed this issue by changing the loading query to SELECT * FROM player as p, playerdata as pd WHERE p.username = '" + name + "' AND pd.username = '" + name + "'
If you want to insert duplicate record in your database, please remove primary key(username) from both tables.so you don't want to insert duplicate records, please use JDBC transactions.The following is sample usage;
Server.getConnectionPool().setAutoCommit(false);
Server.getConnectionPool().executeUpdate("INSERT INTO player (username, password) VALUES (" + player + ") ON duplicate KEY UPDATE " + player2);
Server.getConnectionPool().executeUpdate("INSERT INTO playerdata (username, test) VALUES (" + playerData + ") ON duplicate KEY UPDATE " + playerData2);
Server.getConnectionPool().commit();
Details usage can learn here.

Categories

Resources