创建一个这样的数据库表:
image.png
1.创建sqlite数据库,用于创建数据库、表、属性的初始化、更新等操作。
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
*这个类主要生成一 个数据库,并对数据库的版本进行管理
**/
public class MyOpenHelp extends SQLiteOpenHelper {
public MyOpenHelp(Context context) {
super(context, "xueji.db", null, 1);
}
/**
* 当数据库第一次调用时
* 特别适合做表结构的初始化
* @param sqLiteDatabase
*/
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("create table IF NOT EXISTS xuesheng(_id integer primary key autoincrement,id varchar(20),name varchar(20),age int,sex Boolean)");
}
/**
* 用于数据库更新, 可以执行修改表结构等语句
*/
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
//添加列:添加一个名为 "Birthday" 的新列。
sqLiteDatabase.execSQL("ALTER TABLE xuesheng ADD Birthday date");
//删除列
sqLiteDatabase.execSQL("ALTER TABLE xuesheng DROP COLUMN Birthday");
//改变表中 "Birthday" 列的数据类型
sqLiteDatabase.execSQL("ALTER TABLE Persons ALTER COLUMN Birthday year");
}
}
2.activity中的使用
MyOpenHelp myOpenHelper=new MyOpenHelp(getApplicationContext());
添加:
SQLiteDatabase db=myOpenHelper.getWritableDatabase();
//第一种
ContentValues values=new ContentValues();
values.put("id",XH);
values.put("name",NM);
values.put("age",AG);
values.put("sex",SX);
long insert= db.insert("xuesheng",null,values);
if (insert>0){
Toast.makeText(getApplicationContext(),"添加成功",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(),"添加失败",Toast.LENGTH_SHORT).show();
}
//第二种
db.execSQL("insert into xuesheng(name,age) values('xiaoming','15')")
db.close();//数据库用完关闭
修改:
SQLiteDatabase db=myOpenHelper.getWritableDatabase();
//第一种
ContentValues values=new ContentValues();
values.put("name",name.getText().toString());
values.put("age",age.getText().toString());
values.put("sex",xingbie);
db.update("xuesheng",values,"id=?",new String[]{z_ID});
//第二种
String sql = "update xuesheng set name = "xiaohong" where id = 1";
db.execSQL(sql);
db.close();
查询:
SQLiteDatabase db=myOpenHelper.getReadableDatabase();
//第一种
Cursor cursor=db.rawQuery("select * from xuesheng where id=? and name=? and age=? and sex=?", new String[]{z_ID,z_NAME,z_AGE,z_SEX});
if (cursor!=null&&cursor.getCount()>0){
while (cursor.moveToNext()){
String id=cursor.getString(cursor.getColumnIndex("id"));
String name=cursor.getString(cursor.getColumnIndex("name"));
String Age=cursor.getString(cursor.getColumnIndex("age"));
double age=Double.parseDouble(Age);
String Sex=cursor.getString(cursor.getColumnIndex("sex"));
}
} else
Show("查询0条结果");
db.close();
删除:
//第一种
SQLiteDatabase db=myOpenHelper.getWritableDatabase();
db.execSQL("delete from xuesheng where id=?",new Object[]{id});
//第二种
db.delete("xuesheng","id = ?",new Object[]{String.valueOf(id)});
db.close();
删除指定表
String sql ="DROP TABLE xuesheng";
db.execSQL(sql);
// 数据库版本的更新,由原来的1变为2
StuDBHelper dbHelper = new StuDBHelper(getApplicationContext(),"xueji_db",null,2);
SQLiteDatabase db =dbHelper.getReadableDatabase();
一个简单的对查询的封装:
package com.scott.db;
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;
public class DBManager {
private DBHelper helper;
private SQLiteDatabase db;
public DBManager(Context context) {
helper = new DBHelper(context);
//因为getWritableDatabase内部调用了mContext.openOrCreateDatabase(mName, 0, mFactory);
//所以要确保context已初始化,我们可以把实例化DBManager的步骤放在Activity的onCreate里
db = helper.getWritableDatabase();
}
/**
* add persons
* @param persons
*/
public void add(List<Person> persons) {
db.beginTransaction(); //开始事务
try {
for (Person person : persons) {
db.execSQL("INSERT INTO person VALUES(null, ?, ?, ?)", new Object[]{person.name, person.age, person.info});
}
db.setTransactionSuccessful(); //设置事务成功完成
} finally {
db.endTransaction(); //结束事务
}
}
/**
* update person's age
* @param person
*/
public void updateAge(Person person) {
ContentValues cv = new ContentValues();
cv.put("age", person.age);
db.update("person", cv, "name = ?", new String[]{person.name});
}
/**
* delete old person
* @param person
*/
public void deleteOldPerson(Person person) {
db.delete("person", "age >= ?", new String[]{String.valueOf(person.age)});
}
public <T> List<T> getCommonListEntity(Class<T> clazz, String sql, String[] contentvalue) {
List<Map<String, String>> maplist = getCommonListMap(sql, contentvalue);
List<T> entitylist = new ArrayList<>();
try {
for (int i = 0; i < maplist.size(); i++) {
Map<String, String> kvs = maplist.get(i);
T t = clazz.newInstance();
Field[] fields = clazz.getDeclaredFields();
for (Field item : fields) {
item.setAccessible(true); //在用反射时访问私有变量
if (kvs.get(item.getName()) != null) {
t = setItemValues(t, item, kvs.get(item.getName()));
}
}
entitylist.add(t);
}
} catch (Exception e) {
e.printStackTrace();
}
return entitylist;
}
public List<Map<String, String>> getCommonListMap(String sql, String[] contentvalue) {
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
Cursor cursor = db.rawQuery(sql, contentvalue);
while (cursor.moveToNext()) {
Map<String, String> contents = new HashMap<String, String>();
String[] keys = cursor.getColumnNames();
for (int i = 0; i < keys.length; i++) {
contents.put(keys[i], cursor.getString(cursor.getColumnIndex(keys[i])));
}
list.add(contents);
}
cursor.close();
return list;
}
private <T> T setItemValues(T t, Field item, String value) {
try {
if (value == null) return t;
if (item.getGenericType().toString().contains("String")) {//对String类型的判断
item.set(t, value);
}
if (item.getGenericType().toString().contains("int")) {//对int类型的判断
item.set(t, Integer.parseInt(value));
}
if (item.getGenericType().toString().contains("Integer")) {//对int类型的判断
item.set(t, new Integer(value));
}
if (item.getGenericType().toString().contains("long")) {//对long类型的判断
if (value.equals("")) {
item.set(t, 0l);
} else {
item.set(t, Long.valueOf(value));
}
}
if (item.getGenericType().toString().contains("float")) {//对float类型的判断
item.set(t, Float.valueOf(value));
}
if (item.getGenericType().toString().contains("Date")) {//对date类型的判断
if (value.equals("0") || value.equals("")) {
item.set(t, null);
} else {
item.set(t, new Date(Long.valueOf(value)));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return t;
}
/**
* query all persons, return list
* @return List<Person>
*/
public List<Person> query() {
ArrayList<Person> persons = new ArrayList<Person>();
Cursor c = queryTheCursor();
while (c.moveToNext()) {
Person person = new Person();
person._id = c.getInt(c.getColumnIndex("_id"));
person.name = c.getString(c.getColumnIndex("name"));
person.age = c.getInt(c.getColumnIndex("age"));
person.info = c.getString(c.getColumnIndex("info"));
persons.add(person);
}
c.close();
return persons;
}
/**
* query all persons, return cursor
* @return Cursor
*/
public Cursor queryTheCursor() {
Cursor c = db.rawQuery("SELECT * FROM person", null);
return c;
}
/**
* close database
*/
public void closeDB() {
db.close();
}
}
//activity中的使用
例子:
List<FifteenParasModel> equalFistDate = DBManager.getCommonListEntity(FifteenParasModel.class, sql, new String[]{});
SQL语句中一些关键字的用法:
1.进行数据类型转换
cast(pl.PARAM_CONTENT as int)
2.合并
UNION ALL:去重
3.以。。。归类
group by
4.以。。。排序
order by(asc, desc)
eg:ORDER BY di.DISEASE_TYPE, ci.CATTLE_NO DESC
表A记录如下:
aID aNum
1 a20050111
2 a20050112
3 a20050113
4 a20050114
5 a20050115
表B记录如下:
bID bName
1 2006032401
2 2006032402
3 2006032403
4 2006032404
8 2006032408
5.内联
INNER JOIN
eg:
select * from A
inner join B
on A.aID = B.bID
结果如下:
aID aNum bID bName
1 a20050111 1 2006032401
2 a20050112 2 2006032402
3 a20050113 3 2006032403
4 a20050114 4 2006032404
说明inner join并不以谁为基础,它只显示符合条件的记录.
6.左联/右联
LEFT JOIN / RIGHT JOIN
eg:
(1).left join
select * from A
left join B
on A.aID = B.bID
结果如下:
aID aNum bID bName
1 a20050111 1 2006032401
2 a20050112 2 2006032402
3 a20050113 3 2006032403
4 a20050114 4 2006032404
5 a20050115 NULL NULL
这时候left join是以A表的记录为基础的,A可以看成左表,B可以看成右表,left join是以左表为准的.
换句话说,左表(A)的记录将会全部表示出来,而右表(B)只会显示符合搜索条件的记录
(2).right join
同上
7.限制条数
LIMIT
8.判断是否为空
IFNULL(st.name,'') //在string中写 空 ----- ''
一. 主键: (primary key)
一张表中只能有一个主键,它用于索引。
主键不要更新
eg:create table 表名称 (列名称1 数据类型 primary key, 列名称2 数据 类型,列名称3 数据类型, ...);
二. SQLite 约束:
约束是在表的数据列上强制执行的规则,这些是用来限制可以插入到表中的数据类型。
NOT NULL 约束:确保某列不能有NULL值
eg:CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
DEFAULT 约束:当某列没有指定值时,为该列提供默认值
eg: 不能有俩个相同年龄的纪录
CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL DEFAULT 50000.00
);
UNIQUE 约束; 确保某列中的所有值是不同的
eg: CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL UNIQUE,
ADDRESS CHAR(50),
SALARY REAL DEFAULT 50000.00
);
CHECK 约束:确保某列中的所有数据满足一定条件
eg: 所有工资不能为0
CREATE TABLE COMPANY3(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL CHECK(SALARY > 0)
);
网友评论