我有一个sqlite数据库,其中引入了产品名称。我想要做的是,还有另一个列,它计算一个名称被引入的次数。我不想有重复项(这就是为什么UNIQUE设置)所以例如当首先引入“蛋糕”时,计数器设置为1.每次引入蛋糕时,计数器将增加1。
我在这里和谷歌搜索但我找不到任何东西,如果我找到了什么,因为我没有数据库经验,我不知道如何实现它。请你帮我一个片段和一些简短的解释,我想学习,但我找不到太多关于此事的资源。 提前谢谢,祝你有愉快的一天!
这是我的数据库活动:
public class SQLiteCountryAssistant extends SQLiteOpenHelper
{
private static final String DB_NAME = "usingsqlite.db";
private static final int DB_VERSION_NUMBER = 1;
private static final String DB_TABLE_NAME = "countries";
private static final String DB_COLUMN_1_NAME = "country_name";
private static final String DB_COLUMN_2_NAME = "country_counter";
private static final String DB_CREATE_SCRIPT = "create table " + DB_TABLE_NAME +
" (_id integer primary key autoincrement, country_name text UNIQUE,country_counter int);)";
private SQLiteDatabase sqliteDBInstance = null;
public SQLiteCountryAssistant(Context context)
{
super(context, DB_NAME, null, DB_VERSION_NUMBER);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO: Implement onUpgrade
}
@Override
public void onCreate(SQLiteDatabase sqliteDBInstance)
{
Log.i("onCreate", "Creating the database...");
sqliteDBInstance.execSQL(DB_CREATE_SCRIPT);
}
public void openDB() throws SQLException
{
Log.i("openDB", "Checking sqliteDBInstance...");
if(this.sqliteDBInstance == null)
{
Log.i("openDB", "Creating sqliteDBInstance...");
this.sqliteDBInstance = this.getWritableDatabase();
}
}
public void closeDB()
{
if(this.sqliteDBInstance != null)
{
if(this.sqliteDBInstance.isOpen())
this.sqliteDBInstance.close();
}
}
public long insertCountry(String countryName)
{
ContentValues contentValues = new ContentValues();
contentValues.put(DB_COLUMN_1_NAME, countryName);
return this.sqliteDBInstance.insert(DB_TABLE_NAME, null, contentValues);
}
public boolean removeCountry(String countryName)
{
int result = this.sqliteDBInstance.delete(DB_TABLE_NAME, "country_name='" + countryName + "'", null);
if(result > 0)
return true;
else
return false;
}
public long updateCountry(String oldCountryName, String newCountryName)
{
ContentValues contentValues = new ContentValues();
contentValues.put(DB_COLUMN_1_NAME, newCountryName);
return this.sqliteDBInstance.update(DB_TABLE_NAME, contentValues, "country_name='" + oldCountryName + "'", null);
}
public String[] getAllCountries()
{
Cursor cursor = this.sqliteDBInstance.query(DB_TABLE_NAME, new String[] {DB_COLUMN_1_NAME}, null, null, null, null, DB_COLUMN_1_NAME + " ASC");
if(cursor.getCount() >0)
{
String[] str = new String[cursor.getCount()];
int i = 0;
while (cursor.moveToNext())
{
str[i] = cursor.getString(cursor.getColumnIndex(DB_COLUMN_1_NAME));
i++;
}
return str;
}
else
{
return new String[] {};
}
}
}
答案 0 :(得分:2)
您要做的是更改插入功能。它不是只插入数据,而是首先检查该国家是否已经存在。如果是这样,您需要获取当前值,增加它并更新该行。如果没有,则插入计数为1。
你的删除功能需要匹配 - 检查它是否存在并获得计数。如果计数为1,请将其删除。否则获取旧计数,减少它,并更新行。或者,您可以允许它的计数为0而不执行删除,但是您需要从get查询中删除该行,我真的不建议这样做。
如果性能不是问题,您可以在每个2或3个查询的代码中执行此操作。如果这是一个问题,您可以使用一些花哨的原始SQL查询来减少数据库往返次数。