Chinaunix首页 | 论坛 | 博客
  • 博客访问: 291928
  • 博文数量: 82
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 874
  • 用 户 组: 普通用户
  • 注册时间: 2015-03-21 09:58
个人简介

traveling in cumputer science!!

文章分类

全部博文(82)

文章存档

2016年(13)

2015年(69)

我的朋友

分类: Android平台

2015-07-30 22:10:21

声明:文章原创,转载需注明出处。由于文章大多是学习过程中的记录内容,技术能力有限,希望大家指出其中错误,共同交流进步。由此原因,文章会不定期改善,看原文最新内容,请到:http://blog.chinaunix.net/uid/29454152.html
通过一个demo程序测试了SQLite的语句应用。里面涉及到,数据库建立,表的建立,表中数据的添加,更改,删除,查询
1. 数据库的建立
    Android中集成了SQLite数据库,但是不回自动提供数据库,所以我们想应用的话第一步是建立自己的数据库。
    首先引入包   import android.database.sqlite.SQLiteDatabase;
    下面一句话初始化数据库,也就是建立自己命名的数据句 
    db = openOrCreateDatabase(dbName,MODE_PRIVATE,null);
2. 建立表
    执行语句是
    db.execSQL("CREATE TABLE IF NOT EXISTS mytable(id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar(30), score INTEGER);");
    此语句是通过调用SQLiteDatabase的execSQL()方法,在里面书写SQL语句完成的。
3. 数据的添加、更改、删除
    添加
    db.execSQL("INSERT INTO mytable VALUES('61', 'zhang', '5');");
     更改              
    db.execSQL("UPDATE mytable SET name='pei' WHERE id='61';");
     删除             
     db.execSQL("DELETE FROM mytable WHERE id='61';");
4. 数据的查询
    查询可以通过Android的query方法,此方法会返回一个Cursor对象,通过对Cursor对象的各种操作,可以获得所需数据。
    获取对象方法
     Cursor cursor = db.query(tableName,null,null,null,null,null,null);//后面这一堆参数可缺省
    具体实现在下面JAVA代码的90-108行
5. 代码
    .XML

点击(此处)折叠或打开

  1. <RelativeLayout xmlns:android=" />
  2.     xmlns:tools=" android:layout_width="match_parent"
  3.     android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
  4.     android:paddingRight="@dimen/activity_horizontal_margin"
  5.     android:paddingTop="@dimen/activity_vertical_margin"
  6.     android:paddingBottom="@dimen/activity_vertical_margin"
  7.     android:background="@drawable/b2"
  8.     tools:context=".MainActivity">
  9.     //title
  10.     <TextView android:text="Hello SQLite!!"
  11.         android:layout_width="wrap_content"
  12.         android:layout_height="wrap_content"
  13.         android:id="@+id/titleTextView"/>
  14.     //create SQLite
  15.     <Button
  16.         android:text="创建数据库"
  17.         android:layout_width="wrap_content"
  18.         android:layout_height="wrap_content"
  19.         android:id="@+id/initSQL"
  20.         android:layout_below="@+id/titleTextView"
  21.         android:layout_marginTop="20dp"
  22.         android:layout_alignLeft="@+id/titleTextView"
  23.         />
  24.     //create table
  25.     <Button
  26.         android:layout_width="wrap_content"
  27.         android:layout_height="wrap_content"
  28.         android:text="创建表"
  29.         android:id="@+id/createTable"
  30.         android:layout_below="@+id/initSQL"
  31.         android:layout_marginTop="20dp"
  32.         android:layout_alignLeft="@+id/titleTextView"
  33.         />

  34.     //Android modification data
  35.     <Button
  36.         android:layout_width="wrap_content"
  37.         android:layout_height="wrap_content"
  38.         android:text="Android修改数据"
  39.         android:id="@+id/AndroidModData"
  40.         android:layout_below="@+id/createTable"
  41.         android:layout_marginTop="20dp"
  42.         android:layout_alignLeft="@+id/titleTextView"
  43.         />

  44.     //query data
  45.     <Button
  46.         android:layout_width="wrap_content"
  47.         android:layout_height="wrap_content"
  48.         android:text="查询数据"
  49.         android:id="@+id/queryData"
  50.         android:layout_below="@+id/AndroidModData"
  51.         android:layout_marginTop="20dp"
  52.         android:layout_alignLeft="@+id/initSQL"
  53.         />

  54.     //SQL modification data
  55.     <Button
  56.         android:layout_width="wrap_content"
  57.         android:layout_height="wrap_content"
  58.         android:text="SQL 修改数据"
  59.         android:id="@+id/SQLModData"
  60.         android:layout_below="@+id/queryData"
  61.         android:layout_marginTop="20dp"
  62.         android:layout_alignLeft="@+id/initSQL"
  63.         />

  64. </RelativeLayout>
    .JAVA

点击(此处)折叠或打开

  1. package com.example.warrior.sqliteoperator;

  2. import android.app.Activity;
  3. import android.app.AlertDialog;
  4. import android.content.DialogInterface;
  5. import android.database.Cursor;
  6. import android.database.sqlite.SQLiteDatabase;
  7. import android.support.v7.app.ActionBarActivity;
  8. import android.os.Bundle;
  9. import android.view.Menu;
  10. import android.view.MenuItem;
  11. import android.view.View;
  12. import android.widget.Button;
  13. import android.widget.Toast;


  14. public class MainActivity extends Activity {

  15.     private Button initButton;
  16.     private Button tableButton;
  17.     private Button btn_SqlMod;
  18.     private Button btn_AndroidMod;
  19.     private Button btn_Query;
  20.     private final String dbName = "SQLdb";
  21.     private final String tableName = "mytable";
  22.     private SQLiteDatabase db = null;
  23.     private int i = 1;
  24.     @Override
  25.     protected void onCreate(Bundle savedInstanceState) {
  26.         super.onCreate(savedInstanceState);
  27.         setContentView(R.layout.activity_main);
  28.         initButton = (Button)findViewById(R.id.initSQL);
  29.         initButton.setOnClickListener(new View.OnClickListener() {
  30.             @Override
  31.             public void onClick(View v) {
  32.                 db = openOrCreateDatabase(dbName,MODE_PRIVATE,null);
  33.                 Toast.makeText(getApplicationContext(),"create SQLite Success!!", 1000).show();
  34.             }
  35.         });

  36.         //create table
  37.         tableButton = (Button)findViewById(R.id.createTable);
  38.         tableButton.setOnClickListener(new View.OnClickListener() {
  39.             @Override
  40.             public void onClick(View v) {
  41.                 if(db != null){
  42.                     db.execSQL("CREATE TABLE IF NOT EXISTS mytable(id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar(30), score INTEGER);");
  43.                     Toast.makeText(getApplicationContext(),"create table success!!", 1000).show();
  44.                 }else {
  45.                     Toast.makeText(getApplicationContext(),"None SQL", 1000).show();
  46.                 }
  47.             }
  48.         });

  49.         //sql modification data
  50.         btn_SqlMod = (Button)findViewById(R.id.SQLModData);
  51.         btn_SqlMod.setOnClickListener(new View.OnClickListener() {
  52.             @Override
  53.             public void onClick(View v) {
  54.                 if(db != null){
  55.                     db.execSQL("INSERT INTO mytable VALUES('61', 'zhang', '5');");
  56.                     Toast.makeText(getApplicationContext(),"ADD SUCCESS!!",1000).show();
  57.                     db.execSQL("UPDATE mytable SET name='pei' WHERE id='61';");
  58.                     Toast.makeText(getApplicationContext(), "UPDATE SUCCESS!!", 1000).show();
  59.                     db.execSQL("DELETE FROM mytable WHERE id='61';");
  60.                     Toast.makeText(getApplicationContext(), "DELETE SUCCESS!!", 1000).show();
  61.                 }else {
  62.                     Toast.makeText(getApplicationContext(), "NO SQL", 2000).show();
  63.                 }
  64.             }
  65.         });


  66.         btn_Query = (Button)findViewById(R.id.queryData);
  67.         btn_Query.setOnClickListener(new View.OnClickListener() {
  68.             @Override
  69.             public void onClick(View v) {
  70.                 if(db != null){
  71.                     queryData();
  72.                     Toast.makeText(getApplicationContext(), "SELECT SUCCESS!!", 2000).show();
  73.                 }else {
  74.                     Toast.makeText(getApplicationContext(), "NO SQL", 2000).show();
  75.                 }
  76.             }
  77.         });


  78.     }

  79.     public void queryData(){
  80.         Cursor cursor = db.query(tableName,null,null,null,null,null,null);
  81.         String str = "";
  82.         if(cursor.getCount() != 0){
  83.             cursor.moveToFirst();//跳到第一个游标
  84.             for(int i=0;i<cursor.getCount();i= i+1){
  85.                 str = str + cursor.getString(0)+""+cursor.getString(1)+""+cursor.getString(2)+"\n";
  86.                 cursor.moveToNext();//下一个游标
  87.             }
  88.         }
  89.         new AlertDialog.Builder(MainActivity.this).setTitle("query message!!")
  90.                 .setMessage(str)
  91.                 .setNegativeButton("yes", new DialogInterface.OnClickListener() {
  92.                     @Override
  93.                     public void onClick(DialogInterface dialog, int which) {

  94.                     }
  95.                 }).show();
  96.     }


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

  103.     @Override
  104.     public boolean onOptionsItemSelected(MenuItem item) {
  105.         // Handle action bar item clicks here. The action bar will
  106.         // automatically handle clicks on the Home/Up button, so long
  107.         // as you specify a parent activity in AndroidManifest.xml.
  108.         int id = item.getItemId();

  109.         //noinspection SimplifiableIfStatement
  110.         if (id == R.id.action_settings) {
  111.             return true;
  112.         }

  113.         return super.onOptionsItemSelected(item);
  114.     }
  115. }



                    
阅读(1132) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~