如何使用sqlite将数据插入到android中的表中?

时间:2014-02-13 06:54:02

标签: android sqlite fragment

我正在尝试将值插入SQLite数据库。我在数据库中有两个表,但是没有将值插入到我的第二个表中,即mynum表。我使用相同的代码插入第一个表,但它不适用于第二个表。我怎样才能解决这个问题? 这是我的代码

Databasehandler.java

public class Databasehandler extends SQLiteOpenHelper{
    private static final String LOGCAT = null;

    public Databasehandler(Context applicationcontext) {
        super(applicationcontext,"androidsqlite.db", null, 4);
        // TODO Auto-generated constructor stub
        Log.d(LOGCAT,"Database Created");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        String query,query1;    
        query = "CREATE TABLE userlogin ( phoneId INTEGER PRIMARY  KEY,
                                   username TEXT,userid INTEGER,contacts INTEGER)";

        query1 = "CREATE TABLE mynum ( Id INTEGER PRIMARY KEY,num INTEGER)";
        db.execSQL(query1);
        db.execSQL(query);
        //db.execSQL(query1);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        String query,query1;
        query  = "DROP TABLE IF EXISTS userlogin";
        query1 = "DROP TABLE IF EXISTS mynum";
        db.execSQL(query);
        db.execSQL(query1);
        onCreate(db);
    }

    public void communityfragment(HashMap<String, String> queryvalues) {
        // TODO Auto-generated method stub
        SQLiteDatabase database = this.getWritableDatabase();
        ContentValues values    = new ContentValues();
        values.put("num",queryvalues.get("number"));
        database.insert("mynum", null, values);
        database.close();
    }

这是我的CommunityFragment.java类

public class CommunityFragment extends Fragment {
    HashMap<String, String> d=new HashMap<String, String>();
    d.put("number",f);
    //nameValuePairs.add(new BasicNameValuePair("email","abc"));
    Toast.makeText(getActivity(),"incommunityfragment"+d,Toast.LENGTH_LONG).show();
    db.communityfragment(d);

}

2 个答案:

答案 0 :(得分:1)

您的第二个字段数据类型是INTEGER,并且您将字符串传递给它。纠正了。

将num定义为整数

CREATE TABLE mynum ( Id INTEGER PRIMARY KEY,num INTEGER)

但你给的是字符串。

答案 1 :(得分:1)

SQLiteDatabase db    = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("Messsage", msg);
values.put("Name", SenderName);
values.put("GroupName", Groupname);
db.insert("TableName", null, Values);

如需更多参考,请点击此处http://androiddhina.blogspot.in/2015/04/insert-value-in-database-using-sqlite.html