• <noscript id="e0iig"><kbd id="e0iig"></kbd></noscript>
  • <td id="e0iig"></td>
  • <option id="e0iig"></option>
  • <noscript id="e0iig"><source id="e0iig"></source></noscript>
  • Android——使用SQLite數據庫訪問

    SQLite

     

             SQLite,是一款輕型的數據庫,是遵守ACID的關聯式數據庫管理系統,它的設計目標是嵌入式的,而且目前已經在很多嵌入式產品中使用了它,它占用資源非常的低,在嵌入式設備中,可能只需要幾百K的內存就夠了。它能夠支持Windows/Linux/Unix等等主流的操作系統,同時能夠跟很多程序語言相結合,比如 TclC#PHPJava等,還有ODBC接口,同樣比起MysqlPostgreSQL這兩款開源世界著名的數據庫管理系統來講,它的處理速度比他們都快。SQLite第一個Alpha版本誕生于20005月。至今已經有12個年頭,SQLite也迎來了一個版本 SQLite 3已經發布。

     

    一、界面


     

     

    二、程序包結構


     

     

    三、layout中包含2給配置文件,main.xml(里面包含一個ListView控件)和person.xml(與ListView對應的TextView)

    main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
    
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >
    
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="編號"
                android:textSize="18sp" />
    
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="姓名"
                android:textSize="18sp" />
    
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="年齡"
                android:textSize="18sp" />
        </LinearLayout>
    
        <ListView
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/listView"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    
    </LinearLayout>

     

    person.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    
        <TextView
            android:id="@+id/id"
            android:layout_width="120px"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_margin="3dip"
            android:text="TextView"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    
        <TextView
            android:id="@+id/name"
            android:layout_width="180px"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_margin="3dip"
            android:layout_toRightOf="@+id/id"
            android:text="TextView"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    
        <TextView
            android:id="@+id/age"
            android:layout_width="50px"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_margin="3dip"
            android:layout_toRightOf="@+id/name"
            android:text="TextView"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    
    </RelativeLayout>

     

     

    四、AndroidManifest.xml,配置了Android單元測試

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="org.e276.db"
        android:versionCode="1"
        android:versionName="1.0" >
    	
        <uses-sdk android:minSdkVersion="10" />
    
        <application
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name" >
            
             <!-- Android配置單元測試 -->
            <uses-library android:name="android.test.runner" />
            
            <activity
                android:name=".MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    
        <!-- Android配置單元測試 -->
        <instrumentation 
            android:name="android.test.InstrumentationTestRunner" 
            android:targetPackage="org.e276.db" />
        
    </manifest>

     

     

    五、entity

    package org.e276.entity;
    
    /**
     * 實體類
     * 
     * @author miao
     * 
     */
    public class Person {
    
    	private Integer id;
    	private String name;
    	private Integer age;
    
    	public Person() {
    		super();
    	}
    
    	public Person(Integer id, String name, Integer age) {
    		super();
    		this.id = id;
    		this.name = name;
    		this.age = age;
    	}
    
    	public Integer getId() {
    		return id;
    	}
    
    	public void setId(Integer id) {
    		this.id = id;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public Integer getAge() {
    		return age;
    	}
    
    	public void setAge(Integer age) {
    		this.age = age;
    	}
    
    	@Override
    	public String toString() {
    		return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
    	}
    
    }
    

     

     

    六、dao,帶一dao輔助類

    DBHelper.java

    package org.e276.dao;
    
    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    
    /**
     * 數據庫輔助類
     * 
     * @author miao
     * 
     */
    public class DBHelper extends SQLiteOpenHelper {
    
    	/*
    	 * @param context 上下文
    	 * 
    	 * @param name 數據庫名字
    	 * 
    	 * @param factory 游標工廠對象,沒指定就設置為null
    	 * 
    	 * @param version 版本號
    	 */
    	// public DBHelper(Context context, String name, CursorFactory factory,
    	// int version) {
    	// super(context, name, factory, version);
    	// }
    
    	private static final String DB_NAME = "ali.db";
    	private static final int VERSION = 1;
    
    	public DBHelper(Context context) {
    		super(context, DB_NAME, null, VERSION);
    	}
    
    	/**
    	 * 第一次運行的時候創建
    	 */
    	@Override
    	public void onCreate(SQLiteDatabase db) {
    		db.execSQL("CREATE TABLE IF NOT EXISTS person (personid integer primary key autoincrement, name text, age INTEGER)");
    	}
    
    	/**
    	 * 更新的時候
    	 */
    	@Override
    	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    		db.execSQL("DROP TABLE IF EXISTS person");
    		onCreate(db);
    	}
    
    }
    

     

    PersonDao.java

    package org.e276.dao;
    
    import java.util.ArrayList;
    import java.util.List;
    import org.e276.entity.Person;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    /**
     * 實現類
     * @author miao
     *
     */
    public class PersonDao {
    
    	// 輔助類屬性
    	private DBHelper helper;
    
    	/**
    	 * 帶參構造方法,傳入context
    	 * 
    	 * @param context
    	 */
    	public PersonDao(Context context) {
    		helper = new DBHelper(context);
    	}
    
    	/**
    	 * 使用不同的方法刪除記錄1到多條記錄
    	 * 
    	 * @param ids
    	 */
    	public void delete(Integer... ids) {
    		String[] c = new String[ids.length];
    		StringBuffer sb = new StringBuffer();
    		if (ids.length > 0) {
    			for (int i = 0; i < ids.length; i++) {
    				sb.append('?').append(',');
    				// 把整數數組轉換哼字符串數組
    				c[i] = ids[i].toString();
    			}
    			// 刪除最后一個元素
    			sb.deleteCharAt(sb.length() - 1);
    		}
    		SQLiteDatabase db = helper.getWritableDatabase();
    		db.delete("person", "personid in (" + sb.toString() + ")", c);
    		db.close();
    	}
    
    	/**
    	 * 添加紀錄
    	 * 
    	 * @param person
    	 */
    	public void save(Person person) {
    		SQLiteDatabase db = helper.getWritableDatabase();
    		db.execSQL("insert into person (name,age) values(?,?)", new Object[] {
    				person.getName(), person.getAge() });
    		db.close();
    	}
    
    	/**
    	 * 根據id查找
    	 * 
    	 * @param id
    	 * @return
    	 */
    	public Person find(Integer id) {
    		SQLiteDatabase db = helper.getWritableDatabase();
    		Cursor cursor = db.rawQuery("select * from person where personid=?",
    				new String[] { String.valueOf(id) });
    		if (cursor.moveToNext()) {
    			return new Person(cursor.getInt(0), cursor.getString(1),
    					cursor.getInt(2));
    		}
    		return null;
    	}
    
    	/**
    	 * 查找所有的記錄
    	 * 
    	 * @return
    	 */
    	public List<Person> getAll() {
    		List<Person> persons = new ArrayList<Person>();
    		SQLiteDatabase db = helper.getReadableDatabase();
    		Cursor cursor = db.rawQuery("select * from person", null);
    		while (cursor.moveToNext()) {
    			persons.add(new Person(cursor.getInt(0), cursor.getString(1),
    					cursor.getInt(2)));
    		}
    		return persons;
    	}
    
    	/**
    	 * 查詢全部
    	 * 
    	 * @return 游標
    	 */
    	public Cursor getAllPerson() {
    		SQLiteDatabase db = helper.getReadableDatabase();
    		// ListView 里的id是有個下劃線的,所以這里要給個別名_id
    		Cursor cursor = db.rawQuery(
    				"select personid as _id, name,age from person", null);
    		// 這里數據庫不能關閉
    		return cursor;
    	}
    
    }
    

     

     

    六、Activity類

    package org.e276.db;
    
    import org.e276.dao.PersonDao;
    import android.app.Activity;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteCursor;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ListView;
    import android.widget.SimpleCursorAdapter;
    import android.widget.Toast;
    
    public class MainActivity extends Activity {
    
    	// 聲明ListView對象
    	private ListView listView;
    
    	// Dao
    	private PersonDao personDao;
    
    	/** Called when the activity is first created. */
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.main);
    
    		// 獲得listview
    		listView = (ListView) findViewById(R.id.listView);
    		// 實例化dao
    		personDao = new PersonDao(this);
    		// 得到所有的記錄
    		Cursor cursor = personDao.getAllPerson();
    
    		/*
    		 * 參數作用:context:顯示數據的layout,游標:顯示的列名(一定要包含_id),顯示的控件id名
    		 */
    		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
    				R.layout.person, cursor, new String[] { "_id", "name", "age" },
    				new int[] { R.id.id, R.id.name, R.id.age });
    		listView.setAdapter(adapter);
    
    		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    
    			public void onItemClick(AdapterView<?> parent, View view,
    					int position, long id) {
    				ListView lst = (ListView) parent;
    				// 得到其中的一行
    				SQLiteCursor cursor = (SQLiteCursor) lst
    						.getItemAtPosition(position);
    				Toast.makeText(MainActivity.this, cursor.getString(1) + "被選中",
    						Toast.LENGTH_SHORT).show();
    			}
    		});
    	}
    
    }

     

     

    七、test類,導入JUnit3包

    package org.e276.test;
    
    import java.util.List;
    import java.util.Random;
    import org.e276.dao.PersonDao;
    import org.e276.entity.Person;
    import android.database.Cursor;
    import android.test.AndroidTestCase;
    import android.util.Log;
    
    /**
     * 測試類 用的是JUnit3,用4可能會報錯
     * 
     * @author miao
     * 
     */
    public class TestPersonDao extends AndroidTestCase {
    
    	PersonDao personDao = new PersonDao(getContext());
    
    	@Override
    	protected void setUp() throws Exception {
    		personDao = new PersonDao(getContext());
    	}
    
    	/**
    	 * 保存
    	 */
    	public void testSave() {
    		for (int i = 1; i <= 30; i++) {
    			personDao.save(new Person(-1, "用戶" + i, new Random().nextInt(100)));
    		}
    	}
    
    	/**
    	 * 根據id查找
    	 */
    	public void testFind() {
    		Person person = personDao.find(1);
    		Log.i("tag", person.toString());
    	}
    
    	/**
    	 * 查找全部 集合
    	 */
    	public void testFindAll() {
    		List<Person> persons = personDao.getAll();
    		for (Person person : persons) {
    			Log.i("tag", person.toString());
    		}
    	}
    
    	/*
    	 * 使用命令行查看內嵌數據庫 在DOS下輸入adb shell,或在sdk下的adb.exe下輸入該命令
    	 * 
    	 * Sqliteman 這個工具,可以打開db文件
    	 */
    
    	/**
    	 * 查找全部 游標
    	 */
    	public void testGetAll() {
    		Cursor cursor = personDao.getAllPerson();
    		while (cursor.moveToNext()) {
    			StringBuffer sb = new StringBuffer();
    			sb.append("ID:" + cursor.getInt(0));
    			sb.append("\t用戶名:" + cursor.getString(1));
    			sb.append("\t年齡:" + cursor.getInt(2));
    			Log.i("person", sb.toString());
    		}
    	}
    	
    	/**
    	 * 測試刪除多條記錄
    	 */
    	public void testDelete(){
    		personDao.delete(2,5,9);
    	}
    
    }
    

     

    測試時,先運行save方法,向數據庫循環添加紀錄


     

    運行其他方法時,例如testFind(),可以在LogCat里查看得到,前提是添加過濾器。

     

     

    八、查看添加了的數據,可以運行app直接查看,又可以在dos控制臺下輸入命令查看

    使用dir命令查看目錄結構,然后用cd 目錄名進入該目錄,直到找到sdk里面的adb.exe為止。

    接著使用adb shell命令,打開,出現“#”號代表已經打開了該程序。

    ls 代表查看目錄。

    .help代表查看幫助命令,.tables代表查看數據庫的表。

    出現sqlite的時候代表可以使用SQL查詢語句,增刪改都會對數據庫產生作用。

     

    命令參考圖,來自度娘



    查詢的結果(控制臺中出現亂碼是正常的,并不影響真正的查詢結果):


     

     

    九、demo

     Android-DB.zip

     

     

     

     

     

     

    版權聲明:本文為iteye_8400原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。
    本文鏈接:https://blog.csdn.net/iteye_8400/article/details/82546047

    智能推薦

    Android中使用LitePal操控SQLite數據庫

    《第一行代碼》讀書手札 (一)什么是LitePal數據庫 LitePal數據庫是安卓的一個開源庫,我們在以后的開發中,將會遇到許許多多的開源庫,感謝開源社 區;因為開源社區的存在,一些我們需要的功能,不再需要我們從頭開始寫,我們就可以直接使用; (二)配置LitePal 由于LitePal是開源的第三方庫。但是,我們的JDK開發包中,并沒有內置這些第三方包,所有,我們 需要配置一下; 在Andro...

    android中sqlite數據庫的使用

    用一個Demo程序完成sqlite數據庫的增刪查改。 創建數據庫和表 android中使用SQLiteDatabase需要先實現SQLiteOpenHelper類: onCreate只在數據庫被創建時調用,可以在里面創建我們想要的數據庫;sqLiteDatabase.execSQL就是使用SQL語法執行數據庫操作,這里是創建一個表,列名稱為id,name,author,pages和price。每列...

    Android開發學習---SQLite 數據庫的使用

    一.創建數據庫 1.創建MyDatabaseHelper 類繼承SQLiteOpenHelper幫助類,借助這個類就可以對數據庫進行創建和升級。 2.SQLiteOpenHelper 是一個抽象類,必須繼承才能使用。 3.SQLiteOpenHelper 中有兩個抽象方法,分別是onCreate()和 onUpgrade(),我們必須在自己的幫助類里面重寫這兩個方法,然后分別在這兩個方法中去實現創...

    Android使用已有sqlite數據庫——內部存儲

    ——熱愛開源,樂于分享 Android使用已有sqlite數據庫——內部存儲 上一篇介紹了如何在手機sd卡上使用已有的sqlite數據庫,但是如果手機沒有sd卡這個外部存儲,則怎么實現呢?今天講述使用Android手機內部存儲使用已有的sqlite數據庫。 一、拷貝數據庫文件到當前工程 拷貝到res/raw下: 二、代碼: 這是我在利用Android...

    Android 高效的SQLite型數據庫greenDAO使用

    Android 高效的SQLite型數據庫greenDAO使用 使用: 在你project項目的build.gradle配置如下: buildscript { repositories { mavenCentral() } dependencies { classpath ‘org.greenrobot:greendao-gradle-plugin:3.2.2’ } } /...

    猜你喜歡

    HTML中常用操作關于:頁面跳轉,空格

    1.頁面跳轉 2.空格的代替符...

    freemarker + ItextRender 根據模板生成PDF文件

    1. 制作模板 2. 獲取模板,并將所獲取的數據加載生成html文件 2. 生成PDF文件 其中由兩個地方需要注意,都是關于獲取文件路徑的問題,由于項目部署的時候是打包成jar包形式,所以在開發過程中時直接安照傳統的獲取方法沒有一點文件,但是當打包后部署,總是出錯。于是參考網上文章,先將文件讀出來到項目的臨時目錄下,然后再按正常方式加載該臨時文件; 還有一個問題至今沒有解決,就是關于生成PDF文件...

    電腦空間不夠了?教你一個小秒招快速清理 Docker 占用的磁盤空間!

    Docker 很占用空間,每當我們運行容器、拉取鏡像、部署應用、構建自己的鏡像時,我們的磁盤空間會被大量占用。 如果你也被這個問題所困擾,咱們就一起看一下 Docker 是如何使用磁盤空間的,以及如何回收。 docker 占用的空間可以通過下面的命令查看: TYPE 列出了docker 使用磁盤的 4 種類型: Images:所有鏡像占用的空間,包括拉取下來的鏡像,和本地構建的。 Con...

    requests實現全自動PPT模板

    http://www.1ppt.com/moban/ 可以免費的下載PPT模板,當然如果要人工一個個下,還是挺麻煩的,我們可以利用requests輕松下載 訪問這個主頁,我們可以看到下面的樣式 點每一個PPT模板的圖片,我們可以進入到詳細的信息頁面,翻到下面,我們可以看到對應的下載地址 點擊這個下載的按鈕,我們便可以下載對應的PPT壓縮包 那我們就開始做吧 首先,查看網頁的源代碼,我們可以看到每一...

    精品国产乱码久久久久久蜜桃不卡