sqlLite操作

SqlLite建库建表,增删改查DAO,如果不够清楚的话,还可以参考:http://blog.csdn.net/vrix/article/details/6717090


package com.shzz.wms.dao;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;

import com.shzz.wms.common.TableNames;
import com.shzz.wms.pojo.TGoods;
import com.shzz.wms.pojo.TSeller;
import com.shzz.wms.pojo.TStock;

public class SQLiteDatabaseDao {

private SQLiteDatabase mDb;
private Activity activity;

public SQLiteDatabaseDao(Activity activity) {
this.activity = activity;
mDb = activity.openOrCreateDatabase("WeakProject.db",
SQLiteDatabase.CREATE_IF_NECESSARY, null);
}



public int initTSeller(String table, List<TSeller> tsList) {
int resultFlag = 0;
for (TSeller ts : tsList) {
ContentValues values = new ContentValues();
values.put("SellerName", ts.getSellerName());
values.put("Address", ts.getAddress());
values.put("Contact", ts.getContact());
values.put("ContactNum", ts.getContactNum());
mDb.insert(table, null, values);
resultFlag = resultFlag + 1;
}
return resultFlag;
}

/************ 对数据库的操作 ***********************/

// 获取所有数据库的名称
public String[] getDatabasesList() {
return activity.databaseList();
}

// 创建一个数据库
public void createDatabase(String db) {
activity.openOrCreateDatabase(db, SQLiteDatabase.CREATE_IF_NECESSARY,
null);
}

// 删除一个数据库
public void dropDatabase(String db) {

try {
activity.deleteDatabase(db);
} catch (SQLException e) {
Toast.makeText(activity.getApplicationContext(), "删除数据库失败",
Toast.LENGTH_LONG).show();
}
}

/************ 对数据库的表的属性添加修改操作 ***********************/

// 获取某个数据库的表的名称
public String getTablesList() {

Cursor c = mDb
.rawQuery(
"select name from sqlite_master where type='table' order by name",
null);
StringBuffer str = new StringBuffer();
str.append("表的名称为:\n");
while (c.moveToNext()) {
str.append(c.getString(0) + "\n");
}
c.close();
return str.toString();
}

// 创建表
public void createTable(String table) {
try {
String tables[] = table.split(",");
String createMSUserSQL = "create table if not exists " + tables[0]
+ " (User_ID text  primary key not null, "
+ "User_Name text, " + "Branch text, " + "Password text, "
+ "Email text, " + "Role_Code text, " + "User_Dep text, "
+ "Mobile text, " + "Birthday text, " + "LiveAdress text, "
+ "IDCARD text, " + "Position text, " + "Sex text, "
+ "Valid integer, " + "Deleted_Flag integer, "
+ "Created_By text, " + "Created_Date timestamp, "
+ "Updated_By text, " + "Updated_Date timestamp " + ");";
String createTSellerSQL = "create table if not exists " + tables[1]
+ " (" + "ID  integer primary key autoincrement, "
+ "SellerExtraName text, " + "Remark text, "
+ "SellerName text, " + "Address text, " + "Contact text, "
+ "ContactNum text, " + "Deleted_Flag integer, "
+ "Created_By text, " + "Created_Date timestamp, "
+ "Updated_By text, " + "Updated_Date timestamp " + ");";
String createTGoodsSQL = "create table if not exists " + tables[2]
+ "(" + "ID integer primary key autoincrement,"
+ "GoodsID text," + "GoodsName text," + "SellerID integer,"
+ "Specification text," + "Unit text,"
+ "Deleted_Flag integer," + "Created_By text,"
+ "Created_Date timestamp," + "Updated_By text,"
+ "Updated_Date timestamp);";
String createTStockSQL = "create table if not exists " + tables[3]
+ "(" + "ID integer primary key autoincrement,"
+ "StockID integer," + "GoodsID text,"
+ "SellerID integer," + "StockNum integer,"
+ "Deleted_Flag integer," + "Created_By text,"
+ "Created_Date timestamp," + "Updated_By text,"
+ "SellerName text,"+ "Updated_Date timestamp" + ");";

// mDb.execSQL(createMSUserSQL);//用户主表
mDb.execSQL(createTSellerSQL);//商家主表
mDb.execSQL(createTGoodsSQL);//货品主表
mDb.execSQL(createTStockSQL);//库存主表
} catch (SQLException e) {
Toast.makeText(activity.getApplicationContext(), "数据表创建失败",
Toast.LENGTH_LONG).show();
}
}

// 删除一个表
public void dropTable(String table) {

try {
mDb.execSQL("drop table if exists " + table);
Toast.makeText(activity.getApplicationContext(), "数据表删除成功",
Toast.LENGTH_SHORT).show();
} catch (SQLException e) {
Toast.makeText(activity.getApplicationContext(), "数据表删除失败",
Toast.LENGTH_LONG).show();
}
}

// 修改表--重命名表名
public boolean alterTableRenameTable(SQLiteDatabase mDb, String oldTable,
String newTableName) {
try {
mDb.execSQL("alter table " + oldTable + " rename to  "
+ newTableName + ";");

} catch (SQLException e) {
Toast.makeText(activity.getApplicationContext(), "数据表重命名失败",
Toast.LENGTH_LONG).show();
return false;
}
return true;
}

// 修改表--添加一列
// @table 需要修改的table名
// @column 添加的列的名称
// @type 列的类型,如text,varchar等
public boolean alterTableAddColumn(SQLiteDatabase mDb, String table,
String column, String type) {
try {
mDb.execSQL("alter table  " + table + " add column " + column
+ type + " ;");

} catch (SQLException e) {
Toast.makeText(activity.getApplicationContext(), "数据表添加失败",
Toast.LENGTH_LONG).show();
return false;
}
return true;
}

// 获取表的列的名称
public String getTableColumns(String table) {

Cursor c = getAllData(table);
String[] columns = c.getColumnNames();
String str = table + ":\n";
for (String s : columns) {
str += s + "\n";
}
c.close();
return str;
}

/************ 对数据库的表数据增删改查操作 ***********************/
// 添加一条数据
public void insertTSeller(String table, TSeller ts) {
ContentValues values = new ContentValues();
values.put("SellerExtraName", ts.getSellerExtraName());
values.put("SellerName", ts.getSellerName());
values.put("Contact", ts.getContact());
values.put("ContactNum", ts.getContactNum());
values.put("Remark", ts.getRemark());
values.put("Address", ts.getAddress());
values.put("Created_Date", ts.getCreated_Date());
try {
mDb.insert(table, null, values);
Toast.makeText(activity.getApplicationContext(), "添加数据成功!",
Toast.LENGTH_LONG).show();
} catch (SQLException e) {
Toast.makeText(activity.getApplicationContext(), "添加数据失败!",
Toast.LENGTH_LONG).show();
}
}

/*
*
* 删除一条数据
*/
public boolean delete(String table, int id) {
String whereClause = "id=?";
String[] whereArgs = new String[] { String.valueOf(id) };
try {
mDb.delete(table, whereClause, whereArgs);
Toast.makeText(activity.getApplicationContext(), "删除数据成功!",
Toast.LENGTH_LONG).show();
} catch (SQLException e) {
Toast.makeText(activity.getApplicationContext(), "删除数据失败!",
Toast.LENGTH_LONG).show();
return false;
}
return true;
}

/*
*
* 修改一条数据
*/
public void updateTSeller(String table, TSeller ts) {
ContentValues values = new ContentValues();
values.put("SellerName", ts.getSellerName());
values.put("Address", ts.getAddress());
values.put("Contact", ts.getContact());
values.put("ContactNum", ts.getContactNum());
String whereClause = "ID=?";
String[] whereArgs = new String[] { String.valueOf(ts.getId()) };
try {
mDb.update(table, values, whereClause, whereArgs);
Toast.makeText(activity.getApplicationContext(), "修改数据数据成功!",
Toast.LENGTH_LONG).show();
} catch (SQLException e) {
Toast.makeText(activity.getApplicationContext(), "修改数据数据失败!",
Toast.LENGTH_LONG).show();
}
}

public Cursor queryById(String table, int id) {
/*
* 第一个参数String:表名 第二个参数String[]:要查询的列名 第三个参数String:查询条件
* 第四个参数String[]:查询条件的参数 第五个参数String:对查询的结果进行分组 第六个参数String:对分组的结果进行限制
* 第七个参数String:对查询的结果进行排序
*/
String[] columns = new String[] { "id", "username", "info" };
String selection = "id=?";
String[] selectionArgs = { String.valueOf(id) };
String groupBy = null;
String having = null;
String orderBy = null;
return mDb.query(table, columns, selection, selectionArgs, groupBy,
having, orderBy);
}

public Cursor queryBySellerName(String table, String whereArgers) {
/*
* 第一个参数String:表名 第二个参数String[]:要查询的列名 第三个参数String:查询条件
* 第四个参数String[]:查询条件的参数 第五个参数String:对查询的结果进行分组 第六个参数String:对分组的结果进行限制
* 第七个参数String:对查询的结果进行排序
*/
String[] columns = new String[] { "ID", "SellerName", "Address",
"Contact", "ContactNum", "Deleted_Flag", "Created_By",
"Created_Date", "Updated_By", "Updated_Date" };
String selection = "SellerName like ?";
String[] selectionArgs = { "%" + whereArgers + "%" };
String groupBy = null;
String having = null;
String orderBy = null;
return mDb.query(table, columns, selection, selectionArgs, groupBy,
having, orderBy);
}

public Cursor getAllData(String table) {
// 遍历表所有数据
return mDb.rawQuery("select * from " + table, null);
}

public List<TSeller> getTSellerAllPoints(String table) {
List<TSeller> tsList = new ArrayList<TSeller>();
Cursor cursor = mDb.rawQuery("select * from " + table, null);
while (cursor.moveToNext()) {
TSeller point = new TSeller();
point.setId(cursor.getInt(cursor.getColumnIndex("ID")));
point.setSellerExtraName(cursor.getString(cursor.getColumnIndex("SellerExtraName")));
point.setSellerName(cursor.getString(cursor
.getColumnIndex("SellerName")));
point.setContact(cursor.getString(cursor.getColumnIndex("Contact")));
point.setContactNum(cursor.getString(cursor
.getColumnIndex("ContactNum")));
point.setRemark(cursor.getString(cursor.getColumnIndex("Remark")));
point.setAddress(cursor.getString(cursor.getColumnIndex("Address")));

tsList.add(point);
}
cursor.close();
return tsList;
}

public void finish() {
mDb.close();
}

public void truncateTablle(String table) {
mDb.execSQL("delete from " + table);
}


public List<TSeller> getSellerNameBySellerIDs(String t_Seller, String t_Goods,
String goodId) {
List<TSeller> tSellerList = new ArrayList<TSeller>();
String strSQL = "select ID,SellerName from "+ t_Seller +" where ID in (select SellerID from "+t_Goods+" where GoodsID = '"+goodId+"')";
Cursor cursor = mDb.rawQuery(strSQL, null);
while(cursor.moveToNext()){
TSeller point = new TSeller();
point.setId(cursor.getInt(cursor.getColumnIndex("ID")));
point.setSellerName(cursor.getString(cursor.getColumnIndex("SellerName")));
tSellerList.add(point);
}
cursor.close();
return tSellerList;
}

public TGoods getGoodsNameByGoodsIDAndSellerID(String goodsId, int sellerId) {
TGoods tgoods =  new TGoods();
String strSQL = "select GoodsName,Specification,Unit from "+TableNames.T_Goods+" where GoodsID='"+goodsId+"' and SellerID="+sellerId;
Cursor cursor = mDb.rawQuery(strSQL, null);
while(cursor.moveToNext()){
tgoods.setGoodsName(cursor.getString(cursor.getColumnIndex("GoodsName")).trim());
tgoods.setSpecification(cursor.getString(cursor.getColumnIndex("Specification")).trim());
tgoods.setUnit(cursor.getString(cursor.getColumnIndex("Unit")).trim());
break;
}
cursor.close();
return tgoods;
}

public void saveTStock(TStock ts) {
try {
saveTStock(ts,TableNames.T_Stock);
// saveTStockHistory(ts,TableNames.T_StockHistory);
} catch (Exception e) {
e.printStackTrace();
}
}

private void saveTStockHistory(TStock ts, String t_StockHistory) {
// TODO Auto-generated method stub

}

private void saveTStock(TStock ts, String t_Stock) {

ContentValues values = new ContentValues();
values.put("GoodsID", ts.getGoodsID());
values.put("SellerID", ts.getSellerID());
values.put("StockNum", ts.getNum());
values.put("Created_Date", ts.getCreated_Date());
try {
mDb.insert(t_Stock, null, values);
Toast.makeText(activity.getApplicationContext(), "添加数据成功!",
Toast.LENGTH_LONG).show();
} catch (SQLException e) {
Toast.makeText(activity.getApplicationContext(), "添加数据失败!",
Toast.LENGTH_LONG).show();
}

}

public void selectInsertData() {
String strSQL = "select * from "+ TableNames.T_Stock;
Cursor cursor = mDb.rawQuery(strSQL, null);
while(cursor.moveToNext()){
System.out.println(
"ID:"+cursor.getInt(cursor.getColumnIndex("ID"))
+"   GoodsID:"+cursor.getString(cursor.getColumnIndex("GoodsID")).trim()
+"   SellerID:"+cursor.getInt(cursor.getColumnIndex("SellerID"))
+"   StockNum:"+cursor.getInt(cursor.getColumnIndex("StockNum"))
+"   Created_Date:"+cursor.getString(cursor.getColumnIndex("Created_Date"))
);
}
cursor.close();
}


}

你可能感兴趣的:(sql)