導航:首頁 > 操作系統 > android追加資料庫

android追加資料庫

發布時間:2023-03-24 23:38:02

『壹』 android 怎麼往資料庫裡面添加數據

一、引入
資料庫創建的問題解決了,接下來就該使用資料庫實現應用程序功能的時候了。基
本的操作包括創建、讀取、更新、刪除,即我們通常說的 CRUD(Create, Read, Update, Delete)。
在實現這些操作的時候,我們會使用到兩個比較重要的類 SQLiteDatabase 類和 Cursor 類。

二、創建表
1,execSQL(String sql):執行一條 sql 語句,且執行操作不能為 SELECT
因為它的返回值為 void,所以推薦使用 insert、update 方法等
2.,execSQL (String sql,Object[] bindArgs)
sql:執行一條 sql 語句
bindArgs:為 sql 語句中的?賦值

三、添加數據
1、execSQL(String sql)
2、使用對象的 insert 方法
ContentValues values = new ContentValues();
values.put(USERNAME, user.getUsername());
values.put(PASSWORD, user.getPassword());
db.insert(TABLE_NAME, null, values);
參數:
table:資料庫中的表名
nullColumnHack:指定默認插入欄位,為 null 時能插入數據
values:表示插入欄位所對應的值,使用 put 方法。

四、刪除數據
1、execSQL(String sql)
2、使用對象的 delete 方法
String whereClaues="_id=?";
String [] whereArgs={String.valueOf(id)};
//db.delete(TABLE_NAME, "_id="+id, null);
db.delete(TABLE_NAME, whereClaues, whereArgs);
參數
table:資料庫的表名
whereClause:where 子句,比如:_id=?
whereArgs:where 子句中?的值

五、修改數據
1、execSQL(String sql)
2、使用對象的 delete 方法
ContentValues values = new ContentValues();
values.put(USERNAME, user.getUsername());
values.put(PASSWORD, user.getPassword());
String whereClaues="_id=?";
String [] whereArgs={String.valueOf(user.getId())};
db.update(TABLE_NAME, values, whereClaues, whereArgs);
參數
table:資料庫的表名
values:代表要修改的值,修改方法還是 put(key,values)
whereClause:條件子句,比如 id=?,name=?
whereArgs:為 whereClause 中的?賦值,比如:new String[]{"1","張三"}

圖:

參考代碼:

程序內使用SQLite資料庫是通過SQLiteOpenHelper進行操作

1.自己寫個類繼承SQLiteOpenHelper,重寫以下3個方法

publicvoidonCreate(SQLiteDatabasedb)

{//創建資料庫時的操作,如建表}

publicvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion)

{

//版本更新的操作

}

2.通過SQLiteOpenHelper的getWritableDatabase()獲得一個SQLiteDatabase資料庫,以後的操作都是對SQLiteDatabase進行操作。

3.對得到的SQLiteDatabase對象進行增,改,刪,查等操作。

代碼

packagecx.myNote;

importandroid.content.ContentValues;

importandroid.content.Context;

importandroid.content.Intent;

importandroid.database.Cursor;

importandroid.database.sqlite.SQLiteDatabase;

importandroid.database.sqlite.SQLiteOpenHelper;

//DBOptionsforlogin

publicclassDBOptions{

privatestaticfinalStringDB_NAME="notes.db";

privatestaticfinalStringDB_CREATE="createtablelogininf(nametext,pwdtext)";

{

publicDBHelper(Contextcontext){

super(context,DB_NAME,null,1);

}

@Override

publicvoidonCreate(SQLiteDatabasedb){

//TODOAuto-generatedmethodstub

//建表

db.execSQL(DB_CREATE);

}

@Override

publicvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion){

//TODOAuto-generatedmethodstub

db.execSQL("droptableifexistslogininf");

onCreate(db);

}

}

privateContextcontext;

privateSQLiteDatabasedb;

privateDBHelperdbHelper;

publicDBOptions(Contextcontext)

{

this.context=context;

dbHelper=newDBHelper(context);

db=dbHelper.getReadableDatabase();

}

//自己寫的方法,對資料庫進行操作

publicStringgetName()

{

Cursorcursor=db.rawQuery("selectnamefromlogininf",null);

cursor.moveToFirst();

returncursor.getString(0);

}

publicintchangePWD(StringoldP,Stringpwd)

{

ContentValuesvalues=newContentValues();

values.put("pwd",pwd);

returndb.update("logininf",values,"pwd="+oldP,null);

}

}


insert方法插入的一行記錄使用ContentValus存放,ContentValues類似於Map,它提供了put(String key, Xxx value)(其中key為數據列的列名)方法用於存入數據、getAsXxxx(String key)方法用於取出數據

『貳』 android 中如何導入本地的資料庫

1、單開一個線程:if (isDbFileExist()) { //Do nothing. }else { InputStream is; OutputStream os; try { //In Droid Moto's phone, the following code can not work. is = MainActivity.this.getAssets().open(Constants.DB_FILE_NAME); os = MainActivity.this.openFileOutput(Constants.DB_FILE_NAME, MODE_PRIVATE); byte buffer[] = new byte[1024]; int cnt = is.read(buffer); while (cnt != -1) { os.write(buffer); cnt = is.read(buffer); } is.close(); os.close(); } catch (IOException e) { Log.e(Constants.LOG_TAG, e.getMessage()); } }2、在SQLiteOpenHelper的子類的構造函數中:super(context, context.getFilesDir() + File.separator + Constants.DB_FILE_NAME, null, 1);

『叄』 android怎麼把數據存入資料庫

把數據放入資料庫
通過把ContentValues對象傳入instert()方法把數據插入資料庫:
// Gets the data repository in write mode
SQLiteDatabase db = mDbHelper.getWritableDatabase();
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_ENTRY_ID, id);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, title);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_CONTENT, content);
// Insert the new row, returning the primary key value of the new row
long newRowId;
newRowId = db.insert(
FeedReaderContract.FeedEntry.TABLE_NAME,
FeedReaderContract.FeedEntry.COLUMN_NAME_NULLABLE,
values);
insert()方法的第一個參數是表名。第二個參數提供了框架中的一個列名,在ContentValues的值是空的時候,框架會向表中插入NULL值(如果這個參數是「null」,那麼當沒有值時,框架不會向表中插入一行。
從資料庫中讀取數據
要從資料庫中讀取數據,就要使用query()方法,你需要給這個方法傳入選擇條件和你想要獲取數據的列。查詢結果會在Cursor對象中被返回。
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
FeedReaderContract.FeedEntry._ID,
FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE,
FeedReaderContract.FeedEntry.COLUMN_NAME_UPDATED,
...
};
// How you want the results sorted in the resulting Cursor
String sortOrder =
FeedReaderContract.FeedEntry.COLUMN_NAME_UPDATED + " DESC";
Cursor c = db.query(
FeedReaderContract.FeedEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
使用Cursor對象的移動方法來查看游標中的一行數據,在開始讀取數據之前必須先調用這個方法。通常,應該從調用moveToFirst()方法開始,它會把讀取數據的位置放到結果集中第一實體。對於每一行,你可以通過調用Cursor對象的相應的get方法來讀取列的值,如果getString()或getLong()方法。對於每個get方法,你必須把你希望的列的索引位置傳遞給它,你可以通過調用getColumnIndex()或getColumnIndexOrThrow()方法來獲取列的索引。例如:
cursor.moveToFirst();
long itemId = cursor.getLong(
cursor.getColumnIndexOrThrow(FeedReaderContract.FeedEntry._ID)
);
從資料庫中刪除數據
要從一個表中刪除行數據,你需要提供標識行的選擇條件。數據API為創建選擇條件提供了一種機制,它會防止SQL注入。這中機制把選擇條件分成了選擇條件和選擇參數。條件子句定義了要查看的列,並且還允許你使用組合列來進行篩選。參數是用於跟條件綁定的、用戶篩選數據的值。因為這樣不會導致像SQL語句一樣的處理,所以它避免了SQL注入。
// Define 'where' part of query.
String selection = FeedReaderContract.FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";
// Specify arguments in placeholder order.
String[] selelectionArgs = { String.valueOf(rowId) };
// Issue SQL statement.
db.delete(table_name, selection, selectionArgs);
更新資料庫
當你需要編輯資料庫值的時候,請使用update()方法。
這個方法在更新數據時會把insert()方法中內容值的語法跟delete()方法中的where語法結合在一起。
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// New value for one column
ContentValues values = new ContentValues();
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, title);
// Which row to update, based on the ID
String selection = FeedReaderContract.FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";
String[] selelectionArgs = { String.valueOf(rowId) };
int count = db.update(
FeedReaderDbHelper.FeedEntry.TABLE_NAME,
values,
selection,
selectionArgs);

『肆』 android怎麼鏈接資料庫mysql

有點多請耐心看完。
希望能幫助你,還請及時採納謝謝。
一.前言

android連接資料庫的方式有兩種,第一種是通過連接伺服器,再由伺服器讀取資料庫來實現數據的增刪改查,這也是我們常用的方式。第二種方式是android直接連接資料庫,這種方式非常耗手機內存,而且容易被反編譯造成安全隱患,所以在實際項目中不推薦使用。

二.准備工作

1.載入外部jar包

在Android工程中要使用jdbc的話,要導入jdbc的外部jar包,因為在java的jdk中並沒有jdbc的api,我使用的jar包是mysql-connector-java-5.1.18-bin.jar包,網路上有使用mysql-connector-java-5.1.18-bin.jar包的,自己去用的時候發現不兼容,所以下載了比較新版本的,jar包可以去官網下載,也可以去網路,有很多前人們上傳的。

2.導入jar包的方式

方式一:

可以在項目的build.gradle文件中直接添加如下語句導入

compile files('libs/mysql-connector-java-5.1.18-bin.jar')
方式二:下載jar包復制到項目的libs目錄下,然後右鍵復制過來的jar包Add as libs

三.建立資料庫連接

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jdbc);
new Thread(runnable).start();
}

Handler myHandler=new Handler(){

public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
Bundle data=new Bundle();
data=msg.getData();

//System.out.println("id:"+data.get("id").toString()); //輸出第n行,列名為「id」的值
Log.e("TAG","id:"+data.get("id").toString());
TextView tv= (TextView) findViewById(R.id.jdbc);

//System.out.println("content:"+data.get("content").toString());
}
};

Runnable runnable=new Runnable() {
private Connection con = null;

@Override
public void run() {
// TODO Auto-generated method stub
try {
Class.forName("com.mysql.jdbc.Driver");
//引用代碼此處需要修改,address為數據IP,Port為埠號,DBName為數據名稱,UserName為資料庫登錄賬戶,Password為資料庫登錄密碼
con =
//DriverManager.getConnection("jdbc:mysql://192.168.1.202:3306/b2b", "root", "");
DriverManager.getConnection("jdbc:mysql://http://192.168.1.100/phpmyadmin/index.php:8086/b2b",
UserName,Password);

} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

try {
testConnection(con); //測試資料庫連接
} catch (java.sql.SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void testConnection(Connection con1) throws java.sql.SQLException {
try {
String sql = "select * from ecs_users"; //查詢表名為「oner_alarm」的所有內容
Statement stmt = con1.createStatement(); //創建Statement
ResultSet rs = stmt.executeQuery(sql); //ResultSet類似Cursor

//<code>ResultSet</code>最初指向第一行
Bundle bundle=new Bundle();
while (rs.next()) {
bundle.clear();
bundle.putString("id",rs.getString("userid"));
//bundle.putString("content",rs.getString("content"));
Message msg=new Message();
msg.setData(bundle);
myHandler.sendMessage(msg);
}

rs.close();
stmt.close();
} catch (SQLException e) {

} finally {
if (con1 != null)
try {
con1.close();
} catch (SQLException e) {}
}
}
};

注意:

在Android4.0之後,不允許在主線程中進行比較耗時的操作(連接資料庫就屬於比較耗時的操作),需要開一個新的線程來處理這種耗時的操作,沒新線程時,一直就是程序直接退出,開了一個新線程處理直接,就沒問題了。

當然,連接資料庫是需要網路的,千萬別忘了添加訪問網路許可權:

<uses-permission android:name=」android.permission.INTERNET」/>

四.bug點

1.導入的jar包一定要正確

2.連接資料庫一定要開啟新線程

3.資料庫的IP一定要是可以ping通的,區域網地址手機是訪問不了的

4.資料庫所在的伺服器是否開了防火牆,阻止了訪問
————————————————
版權聲明:本文為CSDN博主「shuaiyou_comon」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/shuaiyou_comon/article/details/75647355

閱讀全文

與android追加資料庫相關的資料

熱點內容
投屏流暢的電影網站 瀏覽:207
盜版電影網站推薦 瀏覽:859
邵氏武俠電影100部 瀏覽:132
男主是牛郎鴨子的小說 瀏覽:756
李時珍的電影全部 瀏覽:227
安卓10編譯伺服器硬體配置 瀏覽:957
什麼樣的主機適合當伺服器 瀏覽:856
衣服哪裡進貨app 瀏覽:516
解壓神器魔術 瀏覽:770
寬頻連接2如何連接伺服器地址 瀏覽:365
隨機信號估計演算法 瀏覽:860
安卓如何重壓開槍 瀏覽:377
航天時代飛鵬圖像處理演算法 瀏覽:521
php比較兩個文件 瀏覽:737
加密貨幣市場活躍 瀏覽:334
最便宜的雲盤伺服器架設傳奇 瀏覽:790
java反向工程 瀏覽:110
pdf文檔轉換excel 瀏覽:8
主角叫楚天的都市小說 瀏覽:754
程序員三重境界 瀏覽:871