zoukankan      html  css  js  c++  java
  • Android 数据库SQLite的使用简单Demo

    在手机开发中SQLite的使用demo

    简单的bean类

    Java代码  收藏代码
    1. package com.easyway.android.sql;  
    2. /** 
    3.  * 普通JavaBean 
    4.  * @author longgangbai 
    5.  * 
    6.  */  
    7. public class CityBean {  
    8.     public static final String ID = "_id";  
    9.     public static final String CITY = "city";  
    10.     public static final String CODE = "code";  
    11.       
    12.     private String id;  
    13.     private String city;  
    14.     private String code;  
    15.       
    16.     public String getId() {  
    17.         return id;  
    18.     }  
    19.     public void setId(String id) {  
    20.         this.id = id;  
    21.     }  
    22.     public String getCity() {  
    23.         return city;  
    24.     }  
    25.     public void setCity(String city) {  
    26.         this.city = city;  
    27.     }  
    28.     public String getCode() {  
    29.         return code;  
    30.     }  
    31.     public void setCode(String code) {  
    32.         this.code = code;  
    33.     }  
    34.   
    35. }  

    界面展现类:

    Java代码  收藏代码
    1. package com.easyway.android.sql;  
    2.   
    3. import java.util.ArrayList;  
    4. import java.util.List;  
    5.   
    6. import android.app.Activity;  
    7. import android.content.ContentValues;  
    8. import android.database.Cursor;  
    9. import android.database.sqlite.SQLiteDatabase;  
    10. import android.os.Bundle;  
    11. import android.view.View;  
    12. import android.view.ViewGroup;  
    13. import android.widget.AdapterView;  
    14. import android.widget.BaseAdapter;  
    15. import android.widget.Button;  
    16. import android.widget.EditText;  
    17. import android.widget.ListView;  
    18. import android.widget.TextView;  
    19.   
    20. /** 
    21.  *  
    22.  *  
    23.  * 本例实现SQLite数据库增加、删除、修改、模糊查询操作。这里不是最好的实现方法, 
    24.  * 如想研究SQL如何封装,请详细查看SQLiteDatebase类. 
    25.  * 查看SQL语句:String sql = SQLiteQueryBuilder.buildQueryString(); 
    26.  *  
    27.  *  
    28.  * @author  longgangbai 
    29.  */  
    30. public class AndroidSQL extends Activity {  
    31.     private static String DB_NAME = "mycity.db";  
    32.     private static int DB_VERSION = 1;  
    33.     private static int POSTION;  
    34.     private ListView listview;  
    35.     private Cursor cursor;  
    36.     private SQLiteDatabase db;  
    37.     private SQLiteHelper dbHelper;  
    38.     private ListAdapter listAdapter;  
    39.       
    40.     private EditText etCity;  
    41.     private EditText etCode;  
    42.     private Button bt_add;  
    43.     private Button bt_modify;  
    44.     private Button bt_query;  
    45.       
    46.     private List<CityBean> cityList = new ArrayList<CityBean>();  
    47.     /** Called when the activity is first created. */  
    48.     @Override  
    49.     public void onCreate(Bundle savedInstanceState) {  
    50.         super.onCreate(savedInstanceState);  
    51.         setContentView(R.layout.main);  
    52.           
    53.         etCity = (EditText) findViewById(R.id.etCity);  
    54.         etCode = (EditText) findViewById(R.id.etCode);  
    55.         bt_add = (Button) findViewById(R.id.bt_add);  
    56.         bt_modify = (Button) findViewById(R.id.bt_modify);  
    57.         bt_query = (Button) findViewById(R.id.bt_query);  
    58.           
    59.         try{  
    60.             /* 初始化并创建数据库 */  
    61.             dbHelper = new SQLiteHelper(this, DB_NAME, null, DB_VERSION);  
    62.             /* 创建表 */  
    63.             db = dbHelper.getWritableDatabase();    //调用SQLiteHelper.OnCreate()           
    64.             /* 查询表,得到cursor对象 */  
    65.             cursor = db.query(SQLiteHelper.TB_NAME, null, null, null, null, null, CityBean.CODE + " DESC");  
    66.             cursor.moveToFirst();  
    67.             while(!cursor.isAfterLast() && (cursor.getString(1) != null)){      
    68.                 CityBean city = new CityBean();  
    69.                 city.setId(cursor.getString(0));  
    70.                 city.setCity(cursor.getString(1));  
    71.                 city.setCode(cursor.getString(2));  
    72.                 cityList.add(city);  
    73.                 cursor.moveToNext();  
    74.             }  
    75.         }catch(IllegalArgumentException e){  
    76.             //当用SimpleCursorAdapter装载数据时,表ID列必须是_id,否则报错column '_id' does not exist  
    77.             e.printStackTrace();  
    78.             //当版本变更时会调用SQLiteHelper.onUpgrade()方法重建表 注:表以前数据将丢失  
    79.             ++ DB_VERSION;  
    80.             dbHelper.onUpgrade(db, --DB_VERSION, DB_VERSION);  
    81. //          dbHelper.updateColumn(db, SQLiteHelper.ID, "_"+SQLiteHelper.ID, "integer");  
    82.         }  
    83.         listview = (ListView)findViewById(R.id.listView);  
    84.         listAdapter = new ListAdapter();  
    85.         listview.setAdapter(listAdapter);  
    86.         listview.setOnItemClickListener(new ListView.OnItemClickListener(){  
    87.             @Override  
    88.             public void onItemClick(AdapterView<?> parent, View view, int postion,  
    89.                     long arg3) {  
    90.                 setSelectedValues(postion);  
    91.             }             
    92.         });  
    93.           
    94.         /* 插入表数据并ListView显示更新 */  
    95.         bt_add.setOnClickListener(new Button.OnClickListener(){  
    96.             @Override  
    97.             public void onClick(View arg0) {  
    98.                 if(etCity.getText().length() > 1 && etCode.getText().length() >1){  
    99.                     ContentValues values = new ContentValues();  
    100.                     values.put(CityBean.CITY, etCity.getText().toString().trim());  
    101.                     values.put(CityBean.CODE, etCode.getText().toString().trim());  
    102.                     //插入数据 用ContentValues对象也即HashMap操作,并返回ID号  
    103.                     Long cityID = db.insert(SQLiteHelper.TB_NAME, CityBean.ID, values);  
    104.                     CityBean city = new CityBean();  
    105.                     city.setId(""+cityID);  
    106.                     city.setCity(etCity.getText().toString().trim());  
    107.                     city.setCode(etCode.getText().toString().trim());  
    108.                     cityList.add(city);  
    109.                     listview.setAdapter(new ListAdapter());  
    110.                     resetForm();  
    111.                 }  
    112.             }  
    113.         });  
    114.           
    115.         /* 查询表,模糊条件查询 */  
    116.         bt_query.setOnClickListener(new Button.OnClickListener(){  
    117.             @Override  
    118.             public void onClick(View view) {  
    119.                 cityList.removeAll(cityList);  
    120.                 String sql = null;  
    121.                 String sqlCity = etCity.getText().length() > 0 ? CityBean.CITY + " like '%" + etCity.getText().toString().trim() + "%'" : "";                  
    122.                 String sqlCode = etCode.getText().length() > 0 ? CityBean.CITY + " like '%" + etCity.getText().toString().trim() + "%'" : "";  
    123.                 if( (!"".equals(sqlCity)) && (!"".equals(sqlCode)) ){  
    124.                     sql = sqlCity + " and" + sqlCode;  
    125.                 }else if(!"".equals(sqlCity)){  
    126.                     sql = sqlCity;  
    127.                 }else if(!"".equals(sqlCode)){  
    128.                     sql = sqlCode;  
    129.                 }  
    130.                 cursor = db.query(true, SQLiteHelper.TB_NAME,   
    131.                         new String[]{CityBean.ID, CityBean.CITY, CityBean.CODE},   
    132.                         sql,   
    133.                         null, null, null, null, null);  
    134.                 cursor.moveToFirst();  
    135.                 while(!cursor.isAfterLast() && (cursor.getString(1) != null)){    
    136.                     CityBean city = new CityBean();  
    137.                     city.setId(cursor.getString(0));  
    138.                     city.setCity(cursor.getString(1));  
    139.                     city.setCode(cursor.getString(2));  
    140.                     cityList.add(city);  
    141.                     cursor.moveToNext();  
    142.                 }  
    143.                 listview.setAdapter(new ListAdapter());  
    144.                 resetForm();  
    145.             }  
    146.         });  
    147.           
    148.         /* 修改表数据 */  
    149.         bt_modify.setOnClickListener(new Button.OnClickListener(){  
    150.             @Override  
    151.             public void onClick(View arg0) {  
    152.                 ContentValues values = new ContentValues();  
    153.                 values.put(CityBean.CITY, etCity.getText().toString().trim());  
    154.                 values.put(CityBean.CODE, etCode.getText().toString().trim());  
    155.                 db.update(SQLiteHelper.TB_NAME, values, CityBean.ID + "=" + cityList.get(POSTION).getId(), null);  
    156.                 cityList.get(POSTION).setCity(etCity.getText().toString().trim());  
    157.                 cityList.get(POSTION).setCode(etCode.getText().toString().trim());  
    158.                 listview.setAdapter(new ListAdapter());  
    159.                 resetForm();  
    160.             }  
    161.         });  
    162.     }  
    163.       
    164.     /* 设置选中ListView的值 */  
    165.     public void setSelectedValues(int postion){  
    166.         POSTION = postion;  
    167.         etCity.setText(cityList.get(postion).getCity());  
    168.         etCode.setText(cityList.get(postion).getCode());  
    169.     }  
    170.       
    171.     /* 重值form */  
    172.     public void resetForm(){  
    173.         etCity.setText("");  
    174.         etCode.setText("");  
    175.     }  
    176.       
    177.     @Override  
    178.     protected void onDestroy() {  
    179.         db.delete(SQLiteHelper.TB_NAME, null, null);  
    180.         super.onDestroy();  
    181.     }  
    182.       
    183.     private class ListAdapter extends BaseAdapter{  
    184.         public ListAdapter(){  
    185.             super();  
    186.         }  
    187.         @Override  
    188.         public int getCount() {  
    189.             return cityList.size();  
    190.         }  
    191.   
    192.         @Override  
    193.         public Object getItem(int postion) {  
    194.             return postion;  
    195.         }  
    196.   
    197.         @Override  
    198.         public long getItemId(int postion) {  
    199.             return postion;  
    200.         }  
    201.   
    202.         @Override  
    203.         public View getView(final int postion, View view, ViewGroup parent) {  
    204.             view = getLayoutInflater().inflate(R.layout.listview, null);  
    205.             TextView tv = (TextView) view.findViewById(R.id.tvCity);  
    206.             tv.setText("" + cityList.get(postion).getCity());  
    207.             TextView bu = (TextView) view.findViewById(R.id.btRemove);  
    208.             bu.setText(R.string.delete);  
    209.             bu.setId(Integer.parseInt(cityList.get(postion).getId()));  
    210.               
    211.             /* 删除表数据 */  
    212.             bu.setOnClickListener(new Button.OnClickListener(){  
    213.                 @Override  
    214.                 public void onClick(View view) {  
    215.                     try{  
    216.                         db.delete(SQLiteHelper.TB_NAME, CityBean.ID + "=" + view.getId(), null);  
    217.                         cityList.remove(postion);  
    218.                         listview.setAdapter(new ListAdapter());                       
    219.                     }catch(Exception e){  
    220.                         e.printStackTrace();  
    221.                     }  
    222.                 }  
    223.             });  
    224.             return view;  
    225.         }  
    226.     }  
    227. }  

    SQLite实现类:

    Java代码  收藏代码
    1. package com.easyway.android.sql;  
    2.   
    3. import android.content.Context;  
    4. import android.database.sqlite.SQLiteDatabase;  
    5. import android.database.sqlite.SQLiteOpenHelper;  
    6. import android.database.sqlite.SQLiteDatabase.CursorFactory;  
    7. /** 
    8.  * 实现对表的创建、更新、变更列名操作 
    9.  *  
    10.  * 在Android 中针对少量数据的操作在SQLite操作实现相关功能功能 
    11.  * ,但是必须继承SQLiteOpenHelper,实现相关的功能。 
    12.  *   
    13.  *  
    14.  * @author longgangbai 
    15.  * 
    16.  */  
    17. public class SQLiteHelper extends SQLiteOpenHelper {  
    18.     public static final String TB_NAME = "citys";  
    19.   
    20.     public SQLiteHelper(Context context, String name, CursorFactory factory,  
    21.             int version) {  
    22.         super(context, name, factory, version);  
    23.     }  
    24.       
    25.     /** 
    26.      * 创建新表 
    27.      */  
    28.     @Override  
    29.     public void onCreate(SQLiteDatabase db) {  
    30.         db.execSQL("CREATE TABLE IF NOT EXISTS " +  
    31.                 TB_NAME + "(" +  
    32.                 CityBean.ID + " integer primary key," +  
    33.                 CityBean.CITY + " varchar," +   
    34.                 CityBean.CODE + " integer"+  
    35.                 ")");  
    36.     }  
    37.       
    38.     /** 
    39.      * 当检测与前一次创建数据库版本不一样时,先删除表再创建新表 
    40.      */  
    41.     @Override  
    42.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
    43.         db.execSQL("DROP TABLE IF EXISTS " + TB_NAME);  
    44.         onCreate(db);  
    45.     }  
    46.       
    47.     /** 
    48.      * 变更列名 
    49.      * @param db 
    50.      * @param oldColumn 
    51.      * @param newColumn 
    52.      * @param typeColumn 
    53.      */  
    54.     public void updateColumn(SQLiteDatabase db, String oldColumn, String newColumn, String typeColumn){  
    55.         try{  
    56.             db.execSQL("ALTER TABLE " +  
    57.                     TB_NAME + " CHANGE " +  
    58.                     oldColumn + " "+ newColumn +  
    59.                     " " + typeColumn  
    60.             );  
    61.         }catch(Exception e){  
    62.             e.printStackTrace();  
    63.         }  
    64.     }  
    65.   
    66. }  
  • 相关阅读:
    Boost智能指针——shared_ptr
    Boost.asio的简单使用(timer,thread,io_service类)
    ACE线程管理机制
    利用boost::asio实现一个简单的服务器框架
    【转载】boost::lexical_cast 的使用
    BOOST 实用手册(摘录自校友博客)
    ACE的安装
    Microsoft SQL Server 2000 中的数据转换服务 (DTS)
    将 DTS 用于业务智能解决方案的最佳实践
    [转]理解“Future”
  • 原文地址:https://www.cnblogs.com/shihao/p/2323694.html
Copyright © 2011-2022 走看看