首页 > 系统 > Android > 正文

Android编程之数据库Sql编程实例分析

2020-04-11 11:37:22
字体:
来源:转载
供稿:网友

本文实例讲述了Android编程之数据库Sql编程实现方法。分享给大家供大家参考。具体分析如下:

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

数据库基本操作:创建表,插入,删除可以用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);   }   } }

希望本文所述对大家的Android程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表