【发布时间】:2014-04-08 19:14:21
【问题描述】:
我正在尝试使用for循环语句如下:
for(int i=1; i <= 48; i++) { insertdiary("", ""); }
在我的 MyDB 文件中:
package com.cookbook.data;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.util.Log;
public class MyDB {
private SQLiteDatabase db;
private final Context context;
private final MyDBhelper dbhelper;
// Initializes MyDBHelper instance
public MyDB(Context c){
context = c;
dbhelper = new MyDBhelper(context, Constants.DATABASE_NAME, null,
Constants.DATABASE_VERSION);
}
// Closes the database connection
public void close()
{
db.close();
}
// Initializes a SQLiteDatabase instance using MyDBhelper
public void open() throws SQLiteException
{
try {
db = dbhelper.getWritableDatabase();
} catch(SQLiteException ex) {
Log.v("Open database exception caught", ex.getMessage());
db = dbhelper.getReadableDatabase();
}
}
// Saves a diary entry to the database as name-value pairs in ContentValues instance
// then passes the data to the SQLitedatabase instance to do an insert
public long insertdiary(String title, String content)
{
try{
ContentValues newTaskValue = new ContentValues();
newTaskValue.put(Constants.TITLE_NAME, title);
newTaskValue.put(Constants.CONTENT_NAME, content);
newTaskValue.put(Constants.DATE_NAME, java.lang.System.currentTimeMillis());
return db.insert(Constants.TABLE_NAME, null, newTaskValue);
} catch(SQLiteException ex) {
Log.v("Insert into database exception caught",
ex.getMessage());
return -1;
}
}
// updates a diary entry (existing row)
public boolean updateDiaryEntry(String title, long rowId)
{
ContentValues newValue = new ContentValues();
newValue.put(Constants.TITLE_NAME, title);
return db.update(Constants.TABLE_NAME, newValue, Constants.KEY_ID + "=" + rowId, null)>0;
}
// Reads the diary entries from database, saves them in a Cursor class and returns it from the method
public Cursor getdiaries()
{
Cursor c = db.query(Constants.TABLE_NAME, null, null,
null, null, null, null);
return c;
}
}
我的目标是在首次创建数据库或表时创建 48 个空行,以便我可以进一步更新这些行而不是创建新条目。不幸的是,我使用此代码的尝试很不幸地给了我错误或创建了多于 48 行的行。 有没有人可以帮助我在第一次创建数据库或表时使用此代码创建 48 行? 我感谢所有帮助。 稻谷
【问题讨论】:
-
“我的目标是在第一次创建数据库或表时创建 48 个空行,这样我就可以进一步更新这些行而不是创建新条目。” 这总是一个坏主意当您使用数据库时。只需在数据准备好时插入行。
-
创建“未使用的行”的问题是您需要到处代码来检查“行”是否未使用!在需要时创建一行的成本与所有“检查”代码的成本相比是不值得的!也就是说,如果你得到一行,那么你可以确定它包含有用的数据!
-
创建 48 行没有内容或有一些内容但允许更新它们而不是创建新行怎么样?我这边的问题是我需要将edittext字段分配给相应的行,我将通过它们的id.s来识别行
-
瑞安文森特。对我来说,重要的是空行被分配给特定的编辑文本字段并代表时间表中的一个时间块。
-
是的,我很欣赏这个问题。您希望保留一段时间。没问题,有一个记录时间段及其状态的表(主)。将其移至“详细信息表”以在需要时找到“实际”“时隙”使用。
标签: mysql sql database loops rows