導航:首頁 > 操作系統 > android資料庫怎麼用

android資料庫怎麼用

發布時間:2022-10-18 01:10:39

❶ 如何進行android資料庫操作

在自己Android資料庫接收或發出一個系統action的時候,要名副其實。比如你響應一個view動作,做的確實edit的勾當,你發送一個pick消息,其實你想讓別人做edit的事,這樣都會造成混亂。
一個好的習慣是創建一個輔助類來簡化你的Android資料庫交互。考慮創建一個資料庫適配器,來添加一個與資料庫交互的包裝層。它應該提供直觀的、強類型的方法,如添加、刪除和更新項目。資料庫適配器還應該處理查詢和對創建、打開和關閉資料庫的包裝。
它還常用靜態的Android資料庫常量來定義表的名字、列的名字和列的索引。下面的代碼片段顯示了一個標准資料庫適配器類的框架。它包括一個SQLiteOpenHelper類的擴展類,用於簡化打開、創建和更新資料庫。
import android.content.Context; import android.database.*; import android.database.sqlite.*; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.util.Log; public class MyDBAdapter { // The name and column index of each column in your database. public static final String KEY_NAME=」name」; public static final int NAME_COLUMN = 1; // TODO: Create public field for each column in your table. // SQL Statement to create a new database. private static final String DATABASE_CREATE = 「create table 「 + DATABASE_TABLE + 「 (「 + KEY_ID + 「 integer primary key autoincrement, 「 + KEY_NAME + 「 text not null);」; // Variable to hold the database instance private SQLiteDatabase db; // Context of the application using the database. private final Context context; // Database open/upgrade helper private myDbHelper dbHelper; public MyDBAdapter(Context _context) { context = _context; dbHelper = new myDbHelper(context, DATABASE_NAME, null, DATABASE_VERSION); } public MyDBAdapter open() throws SQLException { db = dbHelper.getWritableDatabase(); return this; } public void close() { db.close(); } public long insertEntry(MyObject _myObject) { ContentValues contentValues = new ContentValues(); // TODO fill in ContentValues to represent the new row return db.insert(DATABASE_TABLE, null, contentValues); } public boolean removeEntry(long _rowIndex) { return db.delete(DATABASE_TABLE, KEY_ID + 「=」 + _rowIndex, null) > 0; } public Cursor getAllEntries () { return db.query(DATABASE_TABLE, new String[] {KEY_ID, KEY_NAME}, null, null, null, null, null); } public MyObject getEntry(long _rowIndex) { MyObject objectInstance = new MyObject(); // TODO Return a cursor to a row from the database and // use the values to populate an instance of MyObject return objectInstance; } public int updateEntry(long _rowIndex, MyObject _myObject) { String where = KEY_ID + 「=」 + _rowIndex; ContentValues contentValues = new ContentValues(); // TODO fill in the ContentValue based on the new object return db.update(DATABASE_TABLE, contentValues, where, null); } private static class myDbHelper extends SQLiteOpenHelper { public myDbHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } // Called when no database exists in // disk and the helper class needs // to create a new one. @Override public void onCreate(SQLiteDatabase _db) { _db.execSQL(DATABASE_CREATE); }

❷ android資料庫創建後怎麼使用

編程的方式使用資料庫

package com.wshouyou.database;

import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.view.Menu;
import android.widget.Toast;

public class DatabaseActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

DBAdapter db = new DBAdapter(this);

//add a contact
/*db.open();
long id = db.insertContact("junli", "[email protected]");
id = db.insertContact("juan zhan", "[email protected]");
db.close();*/

//get all contacts
/*db.open();
Cursor c = db.getAllContacts();
if (c.moveToFirst())
{
do {
DisplayContact(c);
}while (c.moveToNext());
}
db.close();*/

//get a contact
/*db.open();
Cursor c = db.getContact(2);
if (c.moveToFirst())
DisplayContact(c);
else
Toast.makeText(this, "No contact found!", Toast.LENGTH_SHORT).show();
db.close();*/

//update contact
/*db.open();
if ( db.updateContact(1, "Wei-Meng Lee", "[email protected]") )
Toast.makeText(this, "Update successful!", Toast.LENGTH_SHORT).show();
else
Toast.makeText(this, "Update failed!", Toast.LENGTH_SHORT).show();
db.close();*/

//delete a contact
db.open();
if (db.deleteContact(1))
Toast.makeText(this, "Delete successful!", Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "Delete failed!", Toast.LENGTH_LONG).show();
db.close();
}

public void DisplayContact(Cursor c)
{
Toast.makeText(this ,
"id: "+c.getString(0) + "\n" +
"Name: "+c.getString(1) + "\n"+
"Email: "+c.getString(2),
Toast.LENGTH_SHORT).show();
}

}

操作資料庫。

❸ 如何操作android中的資料庫

Android 不自動提供資料庫。在 Android 應用程序中使用 SQLite,必須自己創建資料庫,然後創建表、索引,填充數據。Android 提供了 SQLiteOpenHelper 幫助你創建一個資料庫,你只要繼承 SQLiteOpenHelper 類,就可以輕松的創建資料庫。SQLiteOpenHelper 類根據開發應用程序的需要,封裝了創建和更新資料庫使用的邏輯。SQLiteOpenHelper 的子類,至少需要實現三個方法:
構造函數,調用父類 SQLiteOpenHelper 的構造函數
onCreate()方法;// TODO 創建資料庫後,對資料庫的操作
onUpgrage()方法。// TODO 更改資料庫版本的操作
當你完成了對資料庫的操作(例如你的 Activity 已經關閉),需要調用 SQLiteDatabase 的 Close() 方法來釋放掉資料庫連接。

❹ android sqlite資料庫怎麼用

1.打開資料庫Context類的openDatabase可以打開一個已經存在的資料庫,如果資料庫不存在,將會拋出FileNotFoundException異常。可以通過Context類的createDatabase函數建立一個新的資料庫。通過調用SQLiteDatabase 的execSQL方法,執行一條SQL語句建立一個新的數據表。代碼如下:public DBHelper(Context ctx) {try {//打開已經存在的資料庫 db = ctx.openDatabase(DATABASE_NAME, null); } catch (FileNotFoundException e) {try {//建立新的資料庫 db = ctx.createDatabase(DATABASE_NAME, DATABASE_VERSION, 0, null); //建立數據表 db.execSQL(DATABASE_CREATE); } catch (FileNotFoundException e1) {db = null;}}}2.獲取表中的數據建立一個游標類Cursor 通過SQLiteDatabase 的query方法查詢一個表格。有了Cursor就可以遍歷所有的記錄了。代碼如下:public List<row> fetchAllRows() { ArrayList<row> ret = new ArrayList<row>();try {Cursor c =db.query(DATABASE_TABLE, new String[] { "rowid", "title", "body"}, null, null, null, null, null); int numRows = c.count(); c.first();for (int i = 0; i < numRows; ++i) { Row row = new Row(); row.rowId = c.getLong(0); row.title = c.getString(1); row.body = c.getString(2); ret.add(row); c.next();}} catch (SQLException e) { Log.e("booga", e.toString());}return ret;}</row></row></row>3.添加新的記錄構造一個ContentValues類,通過調用put方法,可以設置一條記錄的屬性。通過調用SQLiteDatabase的insert方法添加一條新的記錄。代碼如下:public void createRow(String title, String body) { ContentValues initialValues = new ContentValues(); initialValues.put("title", title); initialValues.put("body", body); db.insert(DATABASE_TABLE, null, initialValues); }4.刪除記錄直接調用SQLiteDatabase的delete方法,第二個參數是一個SQL條件表達式。代碼如下:public void deleteRow(String str) {

❺ android 如何連接資料庫

這種方式通常連接一個外部的資料庫,第一個參數就是資料庫文件,這個資料庫不是當前項目中生成的,通常放在項目的Assets目錄下,當然也可以在手機內,如上面參數那個目錄,前提是那個文件存在且你的程序有訪問許可權。

另一種使用資料庫的方式是,自己創建資料庫並創建相應的資料庫表,參考下面的代碼:
public class DatabaseHelper extends SQLiteOpenHelper {
//構造,調用父類構造,資料庫名字,版本號(傳入更大的版本號可以讓資料庫升級,onUpgrade被調用)
public DatabaseHelper(Context context) {
super(context, DatabaseConstant.DATABASE_NAME, null, DatabaseConstant.DATABASE_VERSION);
}
//資料庫創建時調用,裡面執行表創建語句.
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(createVoucherTable());
}
//資料庫升級時調用,先刪除舊表,在調用onCreate創建表.
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DatabaseConstant.TABLE_NAME);
onCreate(db);
}
//生成 創建表的SQL語句
private String createVoucherTable() {
StringBuffer sb = new StringBuffer();
sb.append(" CREATE TABLE ").append(DatabaseConstant.TABLE_NAME).append("( ").append(「ID」)
.append(" TEXT PRIMARY KEY, ")
.append(「USER_ID」).append(" INTEGER, ").append(「SMS_CONTENT」).append(" TEXT ) ");
return sb.toString();
}
} 繼承SQLiteOpenHelper並實現裡面的方法.

之後:
//得到資料庫助手類
helper
=
new
DatabaseHelper(context);
//通過助手類,打開一個可讀寫的資料庫連接
SQLiteDatabase
database
=
helper.getReadableDatabase();
//查詢表中所有記錄
database.query(DatabaseConstant.TABLE_NAME,
null,
null,
null,
null,
null,
null);

❻ 如何在android中使用sqlite資料庫

android 中SQliteDatabase資料庫使用SQLiteOpenHelper輔助類來創建SQLite資料庫視圖,如下代碼:
create view 表名 as 定義

SQLiteOpenHelper類是一個輔助類,用於創建或打開資料庫。
該類的使用方法一般是自定義一個子類,繼承自SQLiteOpenHelper,並覆寫其中最關鍵的兩個方法:onCreate(SQLiteDatabase db)和onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)。當新建一個資料庫時會調用前者,一般在裡面做一些創建表或視圖的操作。資料庫版本升級時則會調用後者。
定義好子類後(假如叫SqlHelper),只要調用SqlHelper對象的getReadableDatabase()方法或getWritableDatabase()方法即可返回一個SQLiteDatabase對象。如果是第一次調用,則會創建資料庫。隨後可使用SQLiteDatabase對象的方法進行數據操作,如:execSQL(), insert(), update(), query(), rawQuery(), delete()等。

❼ android 怎麼調用資料庫方法

SQLite也支持SQL標准類型,VARCHAR、CHAR、BIGINT等。
創建資料庫
Android 不自動提供資料庫。在 Android 應用程序中使用 SQLite,必須自己創建資料庫,然後創建表、索引,填充數據。Android 提供了 SQLiteOpenHelper 幫助你創建一個資料庫,只要繼承 SQLiteOpenHelper 類,就可以創建資料庫。繼承了SQLiteOpenHelper的子類,必須實現三個方法:
1、構造函數,調用父類 SQLiteOpenHelper 的構造函數。這個方法需要四個參數:上下文環境(例如,一個 Activity),資料庫名字,一個可選的游標工廠(通常是 Null),一個代表你正在使用的資料庫模型版本的整數。
2、onCreate()方法,它需要一個 SQLiteDatabase 對象作為參數,根據需要對這個對象填充表和初始化數據。
3、onUpgrage() 方法,它需要三個參數,一個 SQLiteDatabase 對象,一個舊的版本號和一個新的版本號,這樣可以清楚如何把一個資料庫從舊的模型轉變到新的模型。

❽ 如何進行Android資料庫操作

Android資料庫操作類實例
實體類:UserInfo.java
package my.db;
import java.io.Serializable;
import android.graphics.drawable.Drawable;
public class UserInfo implements Serializable {
public static final String ID = "_id";
public static final String USERID = "userId";
public static final String TOKEN = "token";
public static final String TOKENSECRET = "tokenSecret";
public static final String USERNAME = "userName";
public static final String USERICON = "userIcon";
private String id;
private String userId; // 用戶id
private String token;
private String tokenSecret;
private String userName;
private Drawable userIcon;
//getter and setter省略
}
SqliteHelper類:
package my.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class SqliteHelper extends SQLiteOpenHelper{
//用來保存UserID、Access Token、Access Secret的表名
public static final String TB_NAME= "users";
public SqliteHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
}
//創建表
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL( "CREATE TABLE IF NOT EXISTS "+
TB_NAME+ "("+
UserInfo. ID+ " integer primary key,"+
UserInfo. USERID+ " varchar,"+
UserInfo. TOKEN+ " varchar,"+
UserInfo. TOKENSECRET+ " varchar,"+
UserInfo. USERNAME+ " varchar,"+
UserInfo. USERICON+ " blob"+
")"
);
Log. e("Database" ,"onCreate" );
}
//更新表
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL( "DROP TABLE IF EXISTS " + TB_NAME );
onCreate(db);
Log. e("Database" ,"onUpgrade" );
}
//更新列
public void updateColumn(SQLiteDatabase db, String oldColumn, String newColumn, String typeColumn){
try{
db.execSQL( "ALTER TABLE " +
TB_NAME + " CHANGE " +
oldColumn + " "+ newColumn +
" " + typeColumn
);
} catch(Exception e){
e.printStackTrace();
}
}
}
CRUD類DataHelper:
package my.db;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.util.Log;
public class DataHelper {
// 資料庫名稱
private static String DB_NAME = "weibo.db";
// 資料庫版本
private static int DB_VERSION = 2;
private SQLiteDatabase db;
private SqliteHelper dbHelper;
public DataHelper(Context context) {
dbHelper = new SqliteHelper(context, DB_NAME, null, DB_VERSION );
db = dbHelper.getWritableDatabase();
}
public void Close() {
db.close();
dbHelper.close();
}
// 獲取users表中的UserID、Access Token、Access Secret的記錄
public List<UserInfo> GetUserList(Boolean isSimple) {
List<UserInfo> userList = new ArrayList<UserInfo>();
Cursor cursor = db.query(SqliteHelper. TB_NAME, null, null , null, null,
null, UserInfo. ID + " DESC");
cursor.moveToFirst();
while (!cursor.isAfterLast() && (cursor.getString(1) != null )) {
UserInfo user = new UserInfo();
user.setId(cursor.getString(0));
user.setUserId(cursor.getString(1));
user.setToken(cursor.getString(2));
user.setTokenSecret(cursor.getString(3));
if (!isSimple) {
user.setUserName(cursor.getString(4));
ByteArrayInputStream stream = new ByteArrayInputStream(cursor.getBlob(5));
Drawable icon = Drawable.createFromStream(stream, "image");
user.setUserIcon(icon);
}
userList.add(user);
cursor.moveToNext();
}
cursor.close();
return userList;
}
// 判斷users表中的是否包含某個UserID的記錄
public Boolean HaveUserInfo(String UserId) {
Boolean b = false;
Cursor cursor = db.query(SqliteHelper. TB_NAME, null, UserInfo.USERID
+ "=?", new String[]{UserId}, null, null, null );
b = cursor.moveToFirst();
Log. e("HaveUserInfo", b.toString());
cursor.close();
return b;
}
// 更新users表的記錄,根據UserId更新用戶昵稱和用戶圖標
public int UpdateUserInfo(String userName, Bitmap userIcon, String UserId) {
ContentValues values = new ContentValues();
values.put(UserInfo. USERNAME, userName);
// BLOB類型
final ByteArrayOutputStream os = new ByteArrayOutputStream();
// 將Bitmap壓縮成PNG編碼,質量為100%存儲
userIcon.compress(Bitmap.CompressFormat. PNG, 100, os);
// 構造SQLite的Content對象,這里也可以使用raw
values.put(UserInfo. USERICON, os.toByteArray());
int id = db.update(SqliteHelper. TB_NAME, values, UserInfo.USERID + "=?" , new String[]{UserId});
Log. e("UpdateUserInfo2", id + "");
return id;
}
// 更新users表的記錄
public int UpdateUserInfo(UserInfo user) {
ContentValues values = new ContentValues();
values.put(UserInfo. USERID, user.getUserId());
values.put(UserInfo. TOKEN, user.getToken());
values.put(UserInfo. TOKENSECRET, user.getTokenSecret());
int id = db.update(SqliteHelper. TB_NAME, values, UserInfo.USERID + "="
+ user.getUserId(), null);
Log. e("UpdateUserInfo", id + "");
return id;
}
// 添加users表的記錄
public Long SaveUserInfo(UserInfo user) {
ContentValues values = new ContentValues();
values.put(UserInfo. USERID, user.getUserId());
values.put(UserInfo. TOKEN, user.getToken());
values.put(UserInfo. TOKENSECRET, user.getTokenSecret());
Long uid = db.insert(SqliteHelper. TB_NAME, UserInfo.ID, values);
Log. e("SaveUserInfo", uid + "");
return uid;
}
// 添加users表的記錄
public Long SaveUserInfo(UserInfo user, byte[] icon) {
ContentValues values = new ContentValues();
values.put(UserInfo. USERID, user.getUserId());
values.put(UserInfo. USERNAME, user.getUserName());
values.put(UserInfo. TOKEN, user.getToken());
values.put(UserInfo. TOKENSECRET, user.getTokenSecret());
if(icon!= null){
values.put(UserInfo. USERICON, icon);
}
Long uid = db.insert(SqliteHelper. TB_NAME, UserInfo.ID, values);
Log. e("SaveUserInfo", uid + "");
return uid;
}
// 刪除users表的記錄
public int DelUserInfo(String UserId) {
int id = db.delete(SqliteHelper. TB_NAME,
UserInfo. USERID + "=?", new String[]{UserId});
Log. e("DelUserInfo", id + "");
return id;
}
public static UserInfo getUserByName(String userName,List<UserInfo> userList){
UserInfo userInfo = null;
int size = userList.size();
for( int i=0;i<size;i++){
if(userName.equals(userList.get(i).getUserName())){
userInfo = userList.get(i);
break;
}
}
return userInfo;
}
}

閱讀全文

與android資料庫怎麼用相關的資料

熱點內容
榮耀v6怎麼隱藏桌面文件夾 瀏覽:798
程序員有女的嗎 瀏覽:504
通訊伺服器中斷是為什麼 瀏覽:644
itextpdf亂碼 瀏覽:641
哪個app製作書法壁紙 瀏覽:196
暗梁支坐是否加密 瀏覽:341
51單片pdf 瀏覽:688
matlab編程習題 瀏覽:64
騰達wifi加密方式 瀏覽:121
ug平移命令 瀏覽:768
釘釘語音通話安全加密有什麼特徵 瀏覽:609
網購領券app哪個好靠譜 瀏覽:618
人民幣數字加密幣轉賬支付貨幣 瀏覽:634
怎麼用cat命令創建mm 瀏覽:689
當今社會程序員好做嗎 瀏覽:222
程序員那麼可愛梓童第幾集求婚 瀏覽:708
程序員大廠指南 瀏覽:777
ubuntupdf閱讀器 瀏覽:4
直針編織能織出加密針法嗎 瀏覽:747
wps加密方式是什麼意思 瀏覽:154