Download 資料庫測試

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Sqllite3 操作簡介
在操作 DOS 環境下操作過程範例
執行 SQL 指令範例
關閉 AVD 即跳離 Sqlite3, 回至 DOS
sqlite3 command
http://www.sqlite.org/lang.html
http://www.tutorialspoint.com/sqlite/sqlite_commands.htm
基本指令
從 Windows 進入 DOS 指令: [cmd]
adb shell
cd /data/data/
mkdir com.example.sqlte3test
cd com.example.sqlte3test
mkdir databases
sqlite3 company.db
create table employee (_id integer primary key, name text not null, age integer, salary integer);
insert into employee values (1, "Lu",50,50000);
insert into employee values (2, "Lee",30,40000);
insert into employee values (3, "Shu",35,35000);
insert into employee values (4, "Hwang",42,45000);
create table employee (_id integer primary key, name varchar(20) not null, age integer(3), salary integer(6));
=> OK
create table Depart (dpno varchar(6) not null primary key, name varchar(20) not null, age integer(3), salary
integer(6));
=> OK
SQLite - CREATE Database
The SQLite sqlite3 command is used to create new SQLite database. You do not need to have any
special privilege to create a database.
Syntax:
Basic syntax of sqlite3 command is as follows:
$sqlite3 DatabaseName.db
Always, database name should be unique within the RDBMS.
Example:
If you want to create new database <testDB.db>, then SQLITE3 statement would be as follows:
$sqlite3 testDB.db
SQLite version 3.7.15.2 2013-01-09 11:53:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>
Above command will create a file testDB.db in the current directory. This file will be used as
database by SQLite engine. If you have noticed while creating database, sqlite3 command will
provide a sqlite>prompt after creating database file successfully.
Once a database is created, you can check it in the list of databases using SQLite
.databases
sqlite>.databases
seq
--0
name
file
--------------- ---------------------main
/home/sqlite/testDB.db
.tables
Use to list all tables under the opened databases.
.schema employee
List the field list.
.quit
You will use SQLite .quit command to come out of the sqlite prompt as follows:
sqlite>.quit
$
.dump
You can use .dump dot command to export complete database in a text file using SQLite
command at command prompt as follows:
$sqlite3 testDB.db .dump > testDB.sql
Above command will convert the entire contents of testDB.db database into SQLite statements
and dump it into ASCII text file testDB.sql. You can do restoration from the generated testDB.sql in
simple way as follows:
$sqlite3 testDB.db < testDB.sql
At this moment your database is empty, so you can try above two procedures once you have few
tables and data in your database. For now, let's proceed to next chapter.
SQLite - Data Type
SQLite data type is an attribute that specifies type of data of any object. Each column, variable and
expression has related data type in SQLite.
You would use these data types while creating your tables. SQLite uses a more general dynamic
type system. In SQLite, the datatype of a value is associated with the value itself, not with its
container.
SQLite Storage Classes:
Each value stored in an SQLite database has one of the following storage classes:
Storage Class Description
NULL
The value is a NULL value.
INTEGER
The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8
bytes depending on the magnitude of the value.
REAL
The value is a floating point value, stored as an 8-byte IEEE
floating point number.
TEXT
BLOB
The value is a text string, stored using the database
encoding (UTF-8, UTF-16BE or UTF-16LE)
The value is a blob of data, stored exactly as it was input.
SQLite storage class is slightly more general than a datatype. The INTEGER storage class, for
example, includes 6 different integer datatypes of different lengths.
SQLite Affinity Type:
SQLite supports the concept of type affinity on columns. Any column can still store any type of data
but the preferred storage class for a column is called its affinity. Each table column in an SQLite3
database is assigned one of the following type affinities:
Affinity
Description
This column stores all data using storage classes NULL, TEXT
TEXT
or BLOB.
NUMERIC
This column may contain values using all five storage classes.
INTEGER
Behaves the same as a column with NUMERIC affinity with an
exception in a CAST expression.
REAL
Behaves like a column with NUMERIC affinity except that it
forces integer values into floating point representation
A column with affinity NONE does not prefer one storage class
over another and no attempt is made to coerce data from one
NONE
storage class into another.
SQLite Affinity and Type Names:
Following table lists down various data type names which can be used while creating SQLite3
tables and corresponding applied affinity also has been shown:
Data Type
Affinity
INTEGER

INT

INTEGER
CHARACTER(20)
TEXT

TINYINT
VARCHAR(255)
BLOB
NONE









REAL
SMALLINT
VARYING
no datatype specified
REAL
CHARACTER(255)
MEDIUMINT
NUMERIC
DOUBLE
NUMERIC
NCHAR(55)
BIGINT
Boolean
Datatype:
DOUBLE
PRECISION
DECIMAL(10,5)
SQLiteNATIVE
does not have a separate Boolean storage class. Instead, Boolean values are stored as
UNSIGNED BIG INT
FLOAT
integers
0 (false) and 1 (true).
CHARACTER(70)
BOOLEAN


INT2
NVARCHAR(100)
DATE
Date and
Time Datatype:


SQLiteINT8
does not have a separate storage class for storing dates and/or times, but SQLite is
TEXT
DATETIME
capable of storing dates and times as TEXT, REAL or INTEGER values.

CLOB
Storage Class
Date Formate
TEXT
A date in a format like "YYYY-MM-DD HH:MM:SS.SSS".
REAL
The number of days since noon in Greenwich on
November 24, 4714 B.C.
INTEGER
The number of seconds since 1970-01-01 00:00:00 UTC.
You can chose to store dates and times in any of these formats and freely convert between formats
using the built-in date and time functions.
Android SQLite database and content provider - Tutorial
http://www.vogella.com/tutorials/AndroidSQLite/article.html
rawQuery
Cursor c=db.rawQuery("SQL_query",null);
int id[]=new int[c.getCount];
int i=0;
if (c.getCount() > 0)
{
c.moveToFirst();
do {
id[i]=c.getInt(c.getColumnIndex("field_name"));
i++;
} while (c.moveToNext());
c.close();
}
Cursor c = sampleDB.rawQuery("SELECT FirstName, Age FROM " +
SAMPLE_TABLE_NAME +
" where Age > 10 LIMIT 5", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("FirstName"));
int age = c.getInt(c.getColumnIndex("Age"));
results.add("" + firstName + ",Age: " + age);
}while (c.moveToNext());
}
}
Example
http://alvinalexander.com/java/jwarehouse/android/core/tests/coretests/src/android/database/DatabaseC
ursorTest.java.shtml
SQLiteOpenHelper 常用方法
getReadableDatabase():建立或開啟唯讀資料庫
getWritableDatabase():建立或開啟可讀寫資料庫
getDatabaseName():取得資料庫名
close():關閉資料庫
範例:
宣告公用物件
SQLiteDatabase myDb;
DatabaseHelper hlp; // DatabaseHelper 類別
Cursor cursor;
建立或開啟資料庫
hlp=new DatabaseHelper(getApplicationContext(),"myappdb.db",null,1);
取得資料庫物件參考
myDb =this.getReadableDatabase();
取得游標物件參考
String str="select * from "+ tbl + ";";
Cursor c=myDb.rawQuery(str,null);
DatabaseHelper 類別
public class DatabaseHelper extends SQLiteOpenHelper {
static Context mContext;
private SQLiteDatabase myDb;
Cursor cursor;
File file;
//建構函式
/*
public DatabaseHelper(Context context, String name,
CursorFactory factory,
int version) {
super(context, name, factory, version);
mContext=context;
}
*/
public DatabaseHelper(Context context, String
name,CursorFactory factory,int version) {
/*
* next code failed
super(context, name, null, version);
//以上指令將資料庫建立在系統內部記憶體
super(context,
context.getExternalFilesDir(null).getAbsolutePath() +
"storage/sdcard1/com.example.myappdb/database/" +
name, null, version); //Fail
*/
super(context,
context.getExternalFilesDir(null).getAbsolutePath() + "/" +
name, null, version);
mContext=context;
//以上指令將資料庫建立在手機 SD card 記憶體
super(context,
storage/sdcard0/android/data/com.example.myappdb/files/" + "/" +
name, null, version); //fail
}
//此方法在建立資料庫時執行
@Override
public void onCreate(SQLiteDatabase db) {
try {
//執行建立資料表的SQL指令
//db.execSQL("drop database myappdb.db");
//db.execSQL("drop table if exists _tblDEF");
//mContext.deleteDatabase("myappdb.db");
myDb=db;
reCreateSys(db);
}
catch(Exception e)
{
Log.e("MainLogger.Run.Exception", "" + e);
//Toast.makeText(DatabaseHelper.this, e.getMessage(),
Toast.LENGTH_LONG).show();
}
finally
{
// txtData.setText("Unknown!");
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
reCreateSys(db);
}
}
SQLiteDatabase 常用方法
參考網站: http://blog.csdn.net/ccwwff/article/details/5834482
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
beginTransaction():以 Exclusive 開始一個交易範圍
beginTransactionNonExclusive():以非 Exclusive 開始一個交易範圍
end Transaction():結束交易範圍
create():建立記憶體備分資料庫
openDatabase()/openOrCreateDatabase():開啟資料庫
insert():新增紀錄
query():查詢紀錄
replace():以新值取代或新增一筆紀錄
update():修改紀錄
delete():刪除紀錄
execSQL():執行 SQL
deleteDatabase():刪除資料路
Cursor
http://siyuantw.blogspot.tw/2013/08/android-sqlite.html
close():關閉 cursor
取欄值
getBlob(index)
getFloat(index)
getInt(index)
getString(index)
getType(index):取型態
範例:
public void getFldValue(String tbl,String fld,String[] ary)
{
myDb =this.getReadableDatabase();
String str="select "+fld+ " from "+ tbl + " order by " + fld +";";
Cursor c=myDb.rawQuery(str,null);
int i;
if (c != null ) {
if (c.moveToFirst()) {
i=0;
do {
switch(c.getType (0))
{
case 1: //1 Cursor.FIELD_TYPE_INTEGER
ary[i]=String.valueOf(c.getInt(0));
break;
case 2: //2 Cursor.FIELD_TYPE_FLOAT
ary[i]=String.valueOf(c.getFloat(0));
break;
case 3: //3 Cursor.FIELD_TYPE_STRING
ary[i]=c.getString(0);
break;
}
i++;
}while(c.moveToNext());
}
}
myDb.close();
return;
}
getColumnCount():取攔數
getCount():取筆數
getPosition():目前記錄位置
isAfterLast():已至末筆之後
isBeforeFirst()已至初筆之前
isFirst():第一筆
isLast():最末筆
isNull(index):空值
move(offset):移至後幾筆
moveToFirst():移至第一筆
moveToLast():移至末筆
moveToNext():移置次筆
moveToPrevious():移置前筆
moveToPosition(position) :移至指定筆
rawQuery():搜尋紀錄 http://www.cnblogs.com/zheng11/archive/2013/04/01/2994533.html
ContentValues
put():加入鍵值對
clear():清除鍵值對
常用 SQL 指令
Create Table [Table_Name] ([Field Definition],[]...,[Primary Key (Field_Name,])
Field Definition : Field_Name Data_Type [null|not null] [default]
Drop Table [Table_Name]
Alter Table [Table_Name] ([New Name]|[New Field])
不能修改舊欄名或定義
資料處理指令
查看紀錄
Select [*|欄位串列] From Table_Name [Where 查詢條件] [Order by [排序欄名]] [Group By [群阻攔名]]
[Limit 筆數]
新增紀錄
Inser Into Table_Name (欄位串列) Values (資料串列)
刪除紀錄
Delete From Table_Name [Where 查詢條件]
修改紀錄
Update Table_Name Set [欄名 = 新值, [欄名 = 新值, ]] Where 搜尋鍵值條件
Related documents