将数据插入特定列

时间:2015-10-12 07:05:33

标签: java android sqlite

我有两个表,一个是Info,另一个是WorkDetails

表格信息:ID(PK), Name, Weather, Date, Status, TimeIn_Info, TimeOut_Info

表工作详细信息:ID(PK),Project,WorkDescription,Per,TimeIn,TimeOut // 4 row

如何在点击按钮时将d值插入两个不同表中的TimeOut和TimeOut_Info?

public void checkRow3(String a, String b, String c, String d) {
    if(!d.equals("null")) {
        WD.insertWorkDetails(a3, a, b, c, d); // working fine
        db.execSQL("INSERT into" + MyDatabaseHelper.TABLE_INFO + "(TimeOut_Info) values(?);", new String[]{d}); //insert d to Table Info column TableOut_Info
        Toast.makeText(this, "Done", Toast.LENGTH_SHORT).show();
        return;
    }
}

这是正确的实施方式吗?

MyDatabaseHelper.java

 public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " + TABLE_INFO + "(ID INTEGER PRIMARY KEY ,Name TEXT,Weather TEXT, Date DATETIME, Status Text, TimeIn_Info DATE TIME, TimeOut_Info DATETIME)");
        db.execSQL("create table " + TABLE_WORKDETAILS + "(ID INTEGER PRIMARY KEY , Project TEXT, WorkDescription TEXT, Per Text, TimeIn DATETIME, TimeOut DATETIME)");
    }

被修改

我改变了这一点,但仍然没有运气

 if (!(TextUtils.isEmpty(d)))
        {
            WD.insertWorkDetails(a3, a, b, c, d);
            db.execSQL("INSERT INTO" +MyDatabaseHelper.TABLE_INFO+"(TimeOut_Info) VALUES (d)");


        }

错误

10-12 07:32:07.942    4814-4814/com.example.project.project E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.project.project, PID: 4814
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.database.sqlite.SQLiteDatabase.execSQL(java.lang.String)' on a null object reference
            at com.example.project.project.WorkDetailsTable.checkRow3(WorkDetailsTable.java:235)
            at com.example.project.project.WorkDetailsTable$1$1.onClick(WorkDetailsTable.java:178)
            at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:153)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5417)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)

2 个答案:

答案 0 :(得分:1)

更改
db.execSQL("INSERT INTO" +MyDatabaseHelper.TABLE_INFO+"(TimeOut_Info) VALUES (d)");

 db = dbHelper.getWritableDatabase();
 ContentValues values = new ContentValues();
 values.put(MyDatabaseHelper.TimeOut_Info, d);
 db.insert(MyDatabaseHelper.TABLE_INFO, null, values);

每次要插入或更新数据库时,请记住编写此语句db = dbHelper.getWritableDatabase();

答案 1 :(得分:0)

创建为两个表插入数据的方法并调用它们。