Android编程5:数据库Sql编程

本文博客链接:http://blog.csdn.net/jdh99,作者:jdh,转载请注明.

Android中安装轻量级数据库Sqlite,现在测试数据库基本操作。

参考hosterZhu的博客,链接:http://blog.csdn.net/hosterZhu/article/details/6133927


数据库基本操作:创建表,插入,删除可以用execSQL();读取可以用rawQuery();这两个函数都可以标准SQL语句进行操作.


源代码:

package com.test.sql;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.util.Log;

public class test_sql extends Activity 
{
	DatabaseHelper mOpenHelper;

	private static final String DATABASE_NAME = "test.db";
	private static final int DATABASE_VERSION = 1;

	private static class DatabaseHelper extends SQLiteOpenHelper {
		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) 
		{
			//新建一个用户表
	                //共有5项:Id Pwd Name OnLineTime Level
			db.execSQL("CREATE TABLE User_Table ('Id' INT,'Pwd' VARCHAR,'Name' VARCHAR,'OnLineTime' INT,'Level' INT)");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		}
	}
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mOpenHelper = new DatabaseHelper(this);
        
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        //清空数据
        db.execSQL("DELETE FROM User_Table");
        //插入数据10000 123456 "jdh" 0 0
        //插入数据10001 123456 "jim" 0 0
        db.execSQL("INSERT INTO User_Table VALUES (?,?,?,?,?)", new Object[]{10000,"123456","jdh",0,0});
        db.execSQL("INSERT INTO User_Table VALUES (?,?,?,?,?)", new Object[]{10001,"123456","jim",0,0});
        //读取数据
        Cursor cursor = db.rawQuery("SELECT * FROM User_Table WHERE Name = ?",new String[]{"jdh"}); 
        while (cursor.moveToNext()) 
        { 
            String str = cursor.getInt(0) + cursor.getString(1) + cursor.getString(2) + cursor.getInt(3) + cursor.getInt(4);
            Log.i("str:", str);
        }   
    }
}


你可能感兴趣的:(sql,编程,android,数据库,table,database)