Android对SQLite的基础操作(用于初学者,少走弯路)

 

 

1.建立DatabaseHelper类并继承SQLiteOpenHelper

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper  extends SQLiteOpenHelper{

 private final static String dataBaseName="sharp.db";
 private final static String tableName="person";
 private final static int version=1;
 public DatabaseHelper(Context context) {
  super(context,dataBaseName,null,version);
  // TODO Auto-generated constructor stub
 }

 @Override
 public void onCreate(SQLiteDatabase db) {
  // TODO Auto-generated method stub
  String sql="CREATE TABLE "+tableName+"(name text not null,age text not null)";
  db.execSQL(sql);
  
 }

 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  // TODO Auto-generated method stub
  
 }

}

2.在ActivityMain类中代码如下:

package com.example.pro08;

import android.os.Bundle;
import android.app.Activity;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
 DatabaseHelper dataHelper=new DatabaseHelper(this);
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
       
        Button btn1=(Button)findViewById(R.id.button1);
        btn1.setOnClickListener(new View.OnClickListener() {
   
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    SQLiteDatabase db = dataHelper.getWritableDatabase();
                String sql="insert into person (name,age) values('wanghe','20')";
               
    
      try {
        Log.i("SQL=", sql);
     
        db.execSQL(sql);
        setTitle("插入数据成功");
       } catch (SQLException e) {
        setTitle("插入数据失败");
       }

   }
  });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

3.在activity_main视图中如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="106dp"
        android:layout_marginTop="94dp"
        android:text="Button" />

</RelativeLayout>

4.然后运行,点击Button,在Tag中可看到

5至于数据库就在你运行后在DDMS中找data/data/你的项目名/database/sharp.db。

同时菜鸟沦落人,互相学习吧

posted @ 2012-11-03 17:20  王贺blog  阅读(172)  评论(0编辑  收藏  举报