1. 安卓資料庫插入數據操作疑問
openOrCreateDatabase
打開或者建立,如果資料庫不存在就建立新的資料庫
insertData
直接執行插入數據,不過你上面的代碼少了一部分,就是沒有建表的sql執行的過程,所以執行insertData時會報錯
2. android怎麼將數據存入資料庫
你通過getText()方法首先得到輸入的值,然後調用資料庫的插入方法 db.insert();插入到資料庫中就行 就想這樣
EditText et ;
String num = et.getText().toString();
public void addData(String num) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("num", num);
db.insert("表名", null, values);
}
當你調用這個 addData()方法時就會向資料庫中插入數據了
3. 安卓開發連接資料庫
Android 連接資料庫
Android採用關系型資料庫SQLite3,它是一個支持SQL輕量級的嵌入式資料庫,在嵌入式操作上有很廣泛的,WM採用的也是SQLite3
關於過於、原理方面的東西在這篇文章里不會提到,但是如果你想能夠快速的學會操作SQLite3,那這就是你要找的文章!
首先,我們看一下api,所有資料庫相關的介面、類都在。database和android.database.sqlite兩個包下,雖然只有兩個包,但是如果你英文不好或是太懶的話也要迷茫一段時間,其實,我們真正用的到的沒有幾個!
1、SQLiteOpenHelper (android.database.sqlite.SQLiteOpenHelper)
這是一個抽象類,關於抽象類我們都知道,如果要使用它,一定是繼承它!
這個類的方法很少,有一個構造方法
SQLiteOpenHelper(android.content.Context context, java.lang.String name,android.database.sqlite.SQLiteDatabase.CursorFactory factory, int version);
參數不做過多的解釋,CursorFactory一般直接傳null就可以
public void onCreate(SQLiteDatabase db)
此方法在創建資料庫是被調用,所以,應該把創建表的操作放到這個方法裡面,一會兒在後面我們會再詳細的說如何創建表
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
從方法名上我們就能知道這個方法是執行更新的,沒錯,當version改變是系統會調用這個方法,所以在這個方法里應該執行刪除現有表,然後手動調用onCreate的操作
SQLiteDatabase getReadableDatabase()
可讀的SQLiteDatabase對象
SQLiteDatabase getWritableDatabase()
獲取可寫的SQLiteDatabase對象
2、SQLiteDatabase(android.database.sqlite.SQLiteDatabase)
關於操作資料庫的工作(增、刪、查、改)都在這個類里
execSQL(sql)
執行SQL語句,用這個方法+SQL語句可以非常方便的執行增、刪、查、改
除此之外,Android還提供了功過方法實現增、刪、查、改
long insert(TABLE_NAME, null, contentValues)添加記錄
int delete(TABLE_NAME, where, whereValue)刪除記錄
int update(TABLE_NAME, contentValues, where, whereValue) 更新記錄
Cursor query(TABLE_NAME, null, null, null, null, null, null) 查詢記錄
除此之外,還有很多方法,如:beginTransaction()開始事務、endTransaction()結束事務…有興趣的可以自己看api,這里就不多贅述了
3、Cursor(android.database.Cursor)
游標(介面),這個很熟悉了吧,Cursor里的方法非常多,常用的有:
boolean moveToPosition(position)將指針移動到某記錄
getColumnIndex(Contacts.People.NAME)按列名獲取id
int getCount()獲取記錄總數
boolean requery()重新查詢
boolean isAfterLast()指針是否在末尾
boolean isBeforeFirst()時候是開始位置
boolean isFirst()是否是第一條記錄
boolean isLast()是否是最後一條記錄
boolean moveToFirst()、 boolean moveToLast()、 boolean moveToNext()同moveToPosition(position)
4、SimpleCursorAdapter(android.widget.SimpleCursorAdapter)
也許你會奇怪了,之前我還說過關於資料庫的操作都在database和database.sqlite包下,為什麼把一個Adapter放到這里,如果你用過Android的SQLite3,你一定會知道
,這是因為我們對資料庫的操作會經常跟列表聯系起來
經常有朋友會在這出錯,但其實也很簡單
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
this,
R.layout.list,
myCursor,
new String[] {DB.TEXT1,DB. TEXT2},
new int[]{ R.id.list1,R.id.listText2 });
my.setAdapter(adapter);
一共5個參數,具體如下:
參數1:Content
參數2:布局
參數3:Cursor游標對象
參數4:顯示的欄位,傳入String[]
參數5:顯示欄位使用的組件,傳入int[],該數組中是TextView組件的id
到這里,關於資料庫的操作就結束了,但是到目前為止我只做了翻譯的工作,有些同學可能還是沒有掌握,放心,下面我們一起順著正常開發的思路理清一下頭緒!
前面的只是幫沒做過的朋友做下普及,下面才是你真正需要的!
一、寫一個類繼承SQLiteOpenHelpe
public class DatabaseHelper extends SQLiteOpenHelper
構造方法:
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
在onCreate方法里寫建表的操作
public void onCreate(SQLiteDatabase db) {
String sql = 「CREATE TABLE tb_test (_id INTEGER DEFAULT '1' NOT NULL PRIMARY KEY AUTOINCREMENT,class_jb TEXT NOT NULL,class_ysbj TEXT NOT NULL,title TEXT NOT NULL,content_ysbj TEXT NOT NULL)」;
db.execSQL(sql);//需要異常捕獲
}
在onUpgrade方法里刪除現有表,然後手動調用onCtreate創建表
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = 「drop table 」+tbname;
db.execSQL(sql);
onCreate(db);
}
對表增、刪、查、改的方法,這里用的是SQLiteOpenHelper提供的方法,也可以用sql語句實現,都是一樣的
關於獲取可讀/可寫SQLiteDatabase,我不說大家也應該會想到,只有查找才會用到可讀的SQLiteDatabase
/**
* 添加數據
*/
public long insert(String tname, int tage, String ttel){
SQLiteDatabase db= getWritableDatabase();//獲取可寫SQLiteDatabase對象
//ContentValues類似map,存入的是鍵值對
ContentValues contentValues = new ContentValues();
contentValues.put(「tname」, tname);
contentValues.put(「tage」, tage);
contentValues.put(「ttel」, ttel);
return db.insert(tbname, null, contentValues);
}
/**
* 刪除記錄
* @param _id
*/
public void delete(String _id){
SQLiteDatabase db= getWritableDatabase();
db.delete(tbname,
「_id=?」,
new String[]{_id});
}
/**
* 更新記錄的,跟插入的很像
*/
public void update(String _id,String tname, int tage, String ttel){
SQLiteDatabase db= getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(「tname」, tname);
contentValues.put(「tage」, tage);
contentValues.put(「ttel」, ttel);
db.update(tbname, contentValues,
「_id=?」,
new String[]{_id});
}
/**
* 查詢所有數據
* @return Cursor
*/
public Cursor select(){
SQLiteDatabase db = getReadableDatabase();
return db.query(
tbname,
new String[]{「_id」,「tname」,「tage」,「ttel」,「taddr」},
null,
null, null, null, 「_id desc」);
}
關於db.query方法的參數,有很多,為了防止大家弄亂,我簡單說一下
參數1:表名
參數2:返回數據包含的列信息,String數組里放的都是列名
參數3:相當於sql里的where,sql里where後寫的內容放到這就行了,例如:tage>?
參數4:如果你在參數3里寫了?(知道我為什麼寫tage>?了吧),那個這里就是代替?的值 接上例:new String[]{「30」}
參數5:分組,不解釋了,不想分組就傳null
參數6:having,想不起來的看看SQL
參數7:orderBy排序
到這里,你已經完成了最多的第一步!我們來看看都用到了那些類:
SQLiteOpenHelper我們繼承使用的
SQLiteDatabase增刪查改都離不開它,即使你直接用sql語句,也要用到execSQL(sql)
二、這里無非是對DatabaseHelper類定義方法的調用,沒什麼可說的,不過我還是對查詢再嘮叨幾句吧
Android查詢出來的結果一Cursor形式返回
cursor = sqLiteHelper.select();//是不是很簡單?
查詢出來的cursor一般會顯示在listView中,這就要用到剛才提到的SimpleCursorAdapter
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
this,
R.layout.list_row,
cursor,
new String[]{「tname」,「ttel」},
new int[]{R.id.TextView01,R.id.TextView02}
);
裡面帶有實例。自己好好學習吧!
4. android sqlite 插入數據失敗的問題
先進調試頁面,
打斷點,單步運行,查看錯誤
3.在debug一欄中查看錯誤信息
這里的錯誤是資料庫表單的項目和實際插入的項目數量不符,原因是這個代碼是修改過的,原來的資料庫表項有52,改成4之後,安卓模擬器里邊的資料庫並沒有刪除,保留原來的4項表單。
解決方法:找到資料庫,資料庫在這里找,這位大哥的博客里有,刪除資料庫。
4.如果不是這個問題,復制錯誤信息,求助網路
5. 如何把鍵盤輸入的數據添加到資料庫中android
你好,解決辦法如下所示:
首先,我們為布局代碼新增一個" 添加數據 "的按鈕。其中,要記得為線性布局設置一個orientation(方向),比如設置為vertical(垂直)。
然後,我們為按鈕設置監聽器,ContentValues對象提供了一個put方法來添加數據。put方法中有兩個參數,第一個參數為資料庫中對應的列名,第二個參數為相應的數據。添加完參數後,我們用SQLiteDatabase對象提供的insert方法把數據插入資料庫。insert方法中有三個參數,第一個參數為表名;第二個參數用於在未添加數據的情況下,自動賦值為NULL,一般傳入null即可;第三個參數為ContentValues對象的值。
如果我們還要傳入一組數據,就要記得在傳入數據之前,添加values.clear()語句來把之前的數據清除掉。
SQL數據的一個主要原則是模式:資料庫是如何組織的一個正式聲明。模式被反映在你用於創建資料庫的SQL語句中。你可能會發現,它有助於創建伴侶類,即約束(contract)類,這個類使用系統性的和自記錄的方式來明確的指定你的模式的布局。約束(contract)類是一個定義URIs、表名和列名的常量容器。在相同包中的所有類都可以這個約束類中的常量。這樣就會一處修改,全局有效。組織約束類的一個好方法是把定義放到類的根層次,以便它對整個資料庫有效。
6. 如何往android中添加資料庫
一、新建外部SQLite資料庫
(1)下載並安裝 SQLite可視化管理工具(SQLite Expert Pro) v3.4.17 破解版
http://www.cr173.com/soft/36343.html
(2)將你手頭上的數據放到EXCEL表格中,保存為CSV格式的數據
(3)在此工具中按照你現有的數據格式新建資料庫和表,如資料庫為:contact.db,表為employee
(4)通過此工具菜單欄中Import/Export下的Import text file(CSV,TSC)功能,將你現有的CSV數據導入到你新建的數據表中(主要目的是省的一個一個的錄入了)
二、在eclipse中新建一個android app工程,並在新建的工程文件夾點右鍵new->folder,在res文件夾下新建raw文件夾(如果有就不用新建了)
三、用滑鼠將新建的SQLite資料庫文件contact.db拖動到新建工程的res下的raw文件下,出現提示,選擇
四、程序代碼
private static final String DATABASE_PATH = "/data/data/你的主程序包路徑(如:com.szair.contact)/databases";
private static final int DATABASE_VERSION = 0;
private static final String DATABASE_NAME = "contact.db";
private static String outFileName = DATABASE_PATH + "/" + DATABASE_NAME;
try {
buildDatabase();//見下
} catch (Exception e) {
e.printStackTrace();
}
//SQLiteDatabase對象
SQLiteDatabase db=SQLiteDatabase.openDatabase(outFileName, null,SQLiteDatabase.NO_LOCALIZED_COLLATORS);
String t="SELECT 欄位名1,欄位名2 FROM employee WHERE **** ORDER BY ***";
Cursor c =db.rawQuery(t, null);
if(c.moveToFirst()){
for(int i=0;i
{
String zian1=c.getString(0);//欄位1的數據
String zian2=c.getString(1);//欄位1的數據
}
}
------------------------------------------------
//前面用到的buildDatabase方法
private void buildDatabase() throws Exception{
InputStream myInput = getResources().openRawResource(R.raw.sz_contact);
File file = new File(outFileName);
File dir = new File(DATABASE_PATH);
if (!dir.exists()) {
if (!dir.mkdir()) {
throw new Exception("創建失敗");
}
}
if (!file.exists()) {
try {
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
myOutput.close();
myInput.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
五、程序發布
按照以上方式,可以將外部建的SQLite資料庫成功的發布出來
7. android 資料庫添加數據後 怎麼在客戶端listView上更新數據
如下:
final SimpleAdapter adapter = new SimpleAdapter(this, getData(),
R.layout.mainlayout, new String[] { "text", "time", "image" },
new int[] { R.id.PL_TextView01, R.id.PL_TextView02,
R.id.PL_ImageView01 });
lv.setAdapter(adapter);
private List<Map<String, Object>> getData() {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Map<String, Object> map = new HashMap<String, Object>();
Cursor cur = DR.query("DB", new String[] { "text", "time" }, null,
null, null, null, "time desc");
while (cur.moveToNext()) {
for (int i = 0; i < cur.getCount(); i++) {
cur.moveToPosition(i);
String text = cur.getString(0);
String time = cur.getString(1);
map = new HashMap<String, Object>();
map.put("text", text);
map.put("time", time);
map.put("image", R.drawable.ic_menu_close_clear_cancel);
list.add(map);
}
}
return list;
}
使用SimpleAdapter 作為listview的適配器 通過數據的query方法 將數據放入listview
8. android往資料庫添加數據後刷新列表,新數據無法顯示
我通常的做法是,自己寫adapter繼承於BaseAdapter,然後加一個setData的公開方法。
在activity中可以開啟一個線程去取數據,取完數據調用handler對listView進行載入或刷新。
如果是載入就new
MyAdapter,listView.setAdapter
如果是刷新就adapter.setData(),
adapter.notifyDataSetChanged().
有不懂再問。