【发布时间】:2010-08-13 20:14:53
【问题描述】:
我正在尝试在 Android SQLite 数据库中插入值。问题是,我正在尝试插入一个单词,该表有 3 列,ID、WORD、COUNT。
当我在数据库中插入一个词时,一些方法会验证这个词是否存在于数据库中。如果是,它将增加该单词的 COUNT 值。
示例。我在数据库中有一个 COUNT 值为 1 的单词“Question”,我想再次插入它,该方法会找到这个单词,如果我想插入“qUeSTion”没关系,它会为我返回“Question”当我检索数据时,它会将 COUNT 的值从 1 增加到 2。明白了吗??
这是我的代码。尝试执行此操作时遇到问题,此验证。我不知道要使用什么方法等。我正在使用 SQLiteStatement 进行插入。但是提供的方法不起作用。知道有什么用吗?
谢谢。
类 DataHelper
public class DataHelper {
private static final String DATABASE_NAME = "sms.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "words";
private Context context;
private SQLiteDatabase db;
private SQLiteStatement insertStmt;
private static final String INSERT = "insert into "
+ TABLE_NAME + "(word) values (?)";
public DataHelper(Context context) {
this.context = context;
OpenHelper openHelper = new OpenHelper(this.context);
this.db = openHelper.getWritableDatabase();
this.insertStmt = this.db.compileStatement(INSERT);
}
public long insert(String word) {
this.insertStmt.bindString(1, word);
return this.insertStmt.executeInsert();
}
public List<String> selectAll() {
List<String> list = new ArrayList<String>();
Cursor cursor = this.db.query(TABLE_NAME, new String[] { "word"},
null, null, null, null, "id desc");
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
}
短信类 这是我获取单词并插入数据库的类
public class SMS extends Activity {
private DataHelper dh;
private static TextView txtView;
final Uri CONTENT_URI = Uri.parse("content://sms/sent");
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.dh = new DataHelper(this);
txtView = (TextView)findViewById(R.id.txtView);
Cursor cursor = getContentResolver().query(CONTENT_URI, null, null, null, null);
String body;
if(cursor.moveToFirst()){
body = cursor.getString(cursor.getColumnIndexOrThrow("body")).toString();
if(body == ""){
Toast.makeText(getBaseContext(), "There is no words to save!", Toast.LENGTH_LONG).show();
}
else{
StringTokenizer st = new StringTokenizer(body);
while(st.hasMoreTokens()){
this.dh.insert(st.nextToken());
Toast.makeText(getBaseContext(), "The set of words has been updated!", Toast.LENGTH_LONG).show();
}
List<String> words = this.dh.selectAll();
StringBuilder sb = new StringBuilder();
sb.append("Set of words:\n\n");
for (String w : words) {
sb.append(w + " ");
}
Log.d("EXAMPLE", "words size - " + words.size());
txtView.setText(sb.toString());
}
}
}
}
【问题讨论】:
-
你应该使用
db.query()和db.update() -
事实上我认为我应该在方法上使用 where 参数。我该怎么做呢? db.query 方法的 where 参数的 sintax 是怎样的?
-
类似于 SQL 字符串,例如:
col1 > 67 and col2 i not null -
您还应该重新考虑列名“Count”,因为它是函数的保留字。
标签: android database sqlite insert