创建数据库并在其中插入多个记录

时间:2013-07-29 04:39:02

标签: android insert sqlite android-sqlite sqliteopenhelper

我想用来自SQLite数据库的数据填充我的listView。但在填充之前,我必须创建数据库并用一些记录填充它。

我有一个sql文件,其中包含插入查询以及要作为记录插入的相应值。

说,它包含查询,如INSERT INTO'tablename'(data1,data2)值('1','2'),('3','4')等。

所以我只需要在SQLite DB中执行相同的查询,并通过在SQLite DB表单中映射此查询来在表中插入数据。对于多个记录插入,我在ThemeTourActivity.java中运行了以下查询,我想在其中显示ListView:

INSERT INTO 'tablename' SELECT 'data1' AS 'col1', 'data2' AS 'col2'
UNION SELECT 'value1', 'value2'
UNION SELECT 'value3', 'value4' 
and so on..

下面是我的SQLiteOpenHelper类:

public class ToursOpenHelper extends SQLiteOpenHelper{
    public static final String DATABASE_NAME="WeTrip_DB";
    public static final int DATABASE_VERSION=1;
    //table's abstract implementations using BASECOLUMNS
    public static abstract class tourEntry implements BaseColumns
    {

        public static final String TABLE="tour";
        public static final String TOURTYPE="tour_type";
        public static final String TOURNAME="tour_name";
        public static final String NIGHTS="nights";
        public static final String DAYS="days";
        public static final String PIC="pic";
    }

    public static abstract class tourcatEntry implements BaseColumns
    {
        public static final String TABLE="tour_cat";
        public static final String TOURCAT_DESC="tourcat_desc";
        public static final String TOURCAT_NAME="tourcat_name";
        public static final String TOURCAT_IMG="tourcat_img";
    }

    public static abstract class tourdestEntry implements BaseColumns
    {
        public static final String TABLE="tour_dest";
        public static final String TOUR_ID="tour_id";
        public static final String DEST_ID="dest_id";
    }

    public static abstract class destEntry implements BaseColumns
    {
        public static final String TABLE="destination";
        public static final String DEST_NAME="dest_name";
    }

    //create DB TABLES
    public static final String CREATE_TABLE_TOUR="CREATE TABLE "+tourEntry.TABLE + 
            "(" 
            + tourEntry._ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
            tourEntry.TOURTYPE + " INTEGER ," +
            tourEntry.TOURNAME + " TEXT ," +
            tourEntry.NIGHTS + " INTEGER ," + 
            tourEntry.DAYS + " INTEGER ,"+
            tourEntry.PIC + " TEXT)";

    public static final String CREATE_TABLE_TOURCAT="CREATE TABLE "+tourcatEntry.TABLE + 
            "(" 
            + tourcatEntry._ID+" INTEGER PRIMARY KEY AUTOINCREMENT , "+
            tourcatEntry.TOURCAT_NAME + " TEXT ," +
            tourcatEntry.TOURCAT_DESC + " TEXT ," +
            tourcatEntry.TOURCAT_IMG + " TEXT)";

    public static final String CREATE_TABLE_TOURDEST="CREATE TABLE "+tourdestEntry.TABLE + 
            "(" 
            + tourdestEntry._ID+" INTEGER PRIMARY KEY AUTOINCREMENT , "+
            tourdestEntry.TOUR_ID + " INTEGER ," +
            tourdestEntry.DEST_ID + " INTEGER)";

    public static final String CREATE_TABLE_DEST="CREATE TABLE "+destEntry.TABLE + 
            "(" 
            + destEntry._ID+" INTEGER PRIMARY KEY AUTOINCREMENT , "+
            destEntry.DEST_NAME + " TEXT)";
    //DELETE DB TABLES
    public static final String DELETE_TABLE_TOUR="DROP TABLE "+tourEntry.TABLE + " IF EXISTS ";
    public static final String DELETE_TABLE_TOURCAT="DROP TABLE "+tourcatEntry.TABLE + " IF EXISTS ";
    public static final String DELETE_TABLE_TOURDEST="DROP TABLE "+tourdestEntry.TABLE + " IF EXISTS ";
    public static final String DELETE_TABLE_DEST="DROP TABLE "+destEntry.TABLE + " IF EXISTS ";

    public ToursOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL(CREATE_TABLE_TOUR);
        db.execSQL(CREATE_TABLE_TOURCAT);
        db.execSQL(CREATE_TABLE_TOURDEST);
        db.execSQL(CREATE_TABLE_DEST);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL(DELETE_TABLE_TOUR);
        db.execSQL(DELETE_TABLE_TOURCAT);
        db.execSQL(DELETE_TABLE_TOURDEST);
        db.execSQL(DELETE_TABLE_DEST);
    }    
}

下面是我的ThemeToursActivity.java,其中必须从DataBase填充listView of tour:

package com.example.travelplanner;

import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class ThemeTourActivity extends Activity implements OnItemClickListener {

    //ArrayList<ThemeTourModel> tour_details = themeTourResults();
    SQLiteDatabase db;
    ToursOpenHelper helper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_theme_tour);
        final ListView tourList = (ListView)findViewById(R.id.theme_tour_listview);
        tourList.setAdapter(new ThemeTourCustomAdapter(this,tour_details));
        tourList.setOnItemClickListener(this);

        helper = new ToursOpenHelper(this);
        db = helper.getWritableDatabase();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.theme_tour, menu);
        return true;
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub

    }

}

我很困惑如何实现这一目标。我只想创建一个数据库,在其中插入多个记录并检索数据并填充listView。如果有人可以指导我完成这项工作,那将是一个很大的帮助。我被困在最后几天。

1 个答案:

答案 0 :(得分:1)

如果要插入值,则可以在SQLHelper类中创建函数,如此

public void InsertData(String Name,int Age,int Address)
    {
        ContentValues values = new ContentValues();  

        values.put("Name",Name); 
        values.put("Age", Age); 
        values.put("Address", Address);

        this.db.insert(Table_Name, null, values);
    }

(在Content值中,您将列名及其值存储在表中);

如果您想获得此值,请执行此操作

public Cursor GetData() throws Exception 
    {   
        Cursor cursor;

        cursor = this.db.query(Table_Name,null, null, null, null, null, null,null );

        return cursor;
    }

如果要获取特定列值,则可以在表名后面传递列名数组。它将返回游标,因此请使用游标适配器作为列表视图。

Cursor c = db.GetData();


ListLayout mCursorAdapter = new ListLayout(
                        getApplicationContext(),                    // The application's Context object
                        R.layout.list_item,        // A layout in XML for one row in the ListView
                        c,                                          // The result from the query
                        new String[] {"Name"},      // A string array of column names in the cursor
                        new int[] { R.id.txtName },0);          // An integer array of view IDs in the row layout


                // Sets the adapter for the ListView
                lv.setAdapter(mCursorAdapter);