
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()方法时就会向数据库中插入数据了
把数据放入数据库通过把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)
*** 作方法是用FileInputStream读取原数据库,再用 FileOutputStream把读取到的东西写入到那个目录。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 packagecom.android.ImportDatabaseimportjava.io.Fileimportjava.io.FileNotFoundExceptionimportjava.io.FileOutputStreamimportjava.io.IOExceptionimportjava.io.InputStreamimportandroid.content.Contextimportandroid.database.sqlite.SQLiteDatabaseimportandroid.os.Environmentimportandroid.util.LogpublicclassDBManager { privatefinalintBUFFER_SIZE =400000publicstaticfinalString DB_NAME ="countries.db"//保存的数据库文件名 publicstaticfinalString PACKAGE_NAME ="com.android.ImportDatabase"publicstaticfinalString DB_PATH ="/data" + Environment.getDataDirectory().getAbsolutePath() +"/" + PACKAGE_NAME//在手机里存放数据库的位置 privateSQLiteDatabase databaseprivateContext contextDBManager(Context context) { this.context = context} publicvoidopenDatabase() { this.database =this.openDatabase(DB_PATH +"/"+ DB_NAME)} privateSQLiteDatabase openDatabase(String dbfile) { try{ if(!(newFile(dbfile).exists())) { //判断数据库文件是否存在,若不存在则执行导入,否则直接打开数据库 InputStream is =this.context.getResources().openRawResource( R.raw.countries)//欲导入的数据库 FileOutputStream fos =newFileOutputStream(dbfile)byte[] buffer =newbyte[BUFFER_SIZE]intcount =0while((count = is.read(buffer)) >0) { fos.write(buffer,0, count)} fos.close()is.close()} SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null)returndb}catch(FileNotFoundException e) { Log.e("Database","File not found")e.printStackTrace()}catch(IOException e) { Log.e("Database","IO exception")e.printStackTrace()} returnnull} ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 packagecom.android.ImportDatabaseimportjava.util.ArrayListimportandroid.app.Activityimportandroid.database.Cursorimportandroid.database.sqlite.SQLiteDatabaseimportandroid.os.BundlepublicclassTaxiActivityextendsActivity { privateSQLiteDatabase databaseArrayList<CityClass>CITY@Override publicvoidonCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState)setContentView(R.layout.main)database = SQLiteDatabase.openOrCreateDatabase(DBManager.DB_PATH +"/"+ DBManager.DB_NAME,null)CITY = getCity()// do something with CITY database.close()} privateArrayList<CityClass>getCity() { Cursor cur = database.rawQuery("SELECT city.id_city, city.name FROM taxi, city WHERE city.id_city = taxi.id_city GROUP BY city.id_city",null)if(cur !=null) { intNUM_CITY = cur.getCount()ArrayList<CityClass>taxicity =newArrayList<CityClass>(NUM_CITY)if(cur.moveToFirst()) { do{ String name = cur.getString(cur.getColumnIndex("name"))intid = cur.getInt(cur.getColumnIndex("id_city"))CityClass city =newCityClass("",0)System.out.println(name)//额外添加一句,把select到的信息输出到Logcat city.city_name = namecity.city_id = idtaxicity.add(city)}while(cur.moveToNext())} returntaxicity}else{ returnnull} } } 查看输出的结果:欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)