关于android中使用SQLite数据库的查询基本操作.贴上代码.
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于android中使用SQLite数据库的查询基本操作.贴上代码.相关的知识,希望对你有一定的参考价值。
DBAdapter.java类部分代码:
package com.example.android_sqlite;
public People[] queryOne(long id)
Cursor results = db.query(DB_TABLE, new String[]KEY_ID, KEY_NAME, KEY_AGE, KEY_HEIGHT, KEY_ID +"="+ id, null, null, null, null);
return ConvertToPeople(results);
public People[] queryAll()
Cursor results = db.query(DB_TABLE, new String[]KEY_ID, KEY_NAME, KEY_AGE, KEY_HEIGHT, null, null, null, null, null);
return ConvertToPeople(results);
private People[] ConvertToPeople (Cursor cursor)
int resultsCount = cursor.getCount();
if(resultsCount == 0 || !cursor.moveToFirst())
return null;
People[] peoples = new People[resultsCount];
for (int i = 0; i < peoples.length; i++)
peoples[i].setId(cursor.getInt(0));
peoples[i].setName(cursor.getString(cursor.getColumnIndex(DB_NAME)));
peoples[i].setAge(cursor.getInt(cursor.getColumnIndex(KEY_AGE)));
peoples[i].setHeight(cursor.getFloat(cursor.getColumnIndex(KEY_HEIGHT)));
cursor.moveToNext();
return peoples;
MainActivity.java类的部分代码:
queryAll.setOnClickListener(new OnClickListener()
@Override
public void onClick(View v)
People[] peoples = dbAdapter.queryAll();
if(peoples == null)
label.setText("数据库中没有数据");
return;
label.setText("数据库:");
String str = "";
for (int i = 0; i < peoples.length; i++)
str += peoples[i].toString() + "\n";
display.setText(str);
);
出现了空指针异常 指向
queryOne.setOnClickListener(new OnClickListener()
@Override
public void onClick(View v)
People[] peoples = dbAdapter.queryOne(Integer.parseInt(id.getText().toString()));
if(peoples == null)
label.setText("数据库中没有ID为" +id.getText().toString()+ "的数据");
return;
label.setText("数据库:");
display.setText(peoples[0].toString());
);
全部查询指向了 People[] peoples = dbAdapter.queryAll();
return ConvertToPeople(results);
id查询指向了 peoples[i].setId(cursor.getInt(0));
return ConvertToPeople(results);
......\.project
......\.settings\org.eclipse.jdt.core.prefs
......\AndroidManifest.xml
......\bin\AndroidManifest.xml
......\...\classes\mars\sqlite3\BuildConfig.class
......\...\.......\....\.......\db\DatabaseHelper.class
......\...\.......\....\.......\R$attr.class
......\...\.......\....\.......\R$drawable.class
......\...\.......\....\.......\R$id.class
......\...\.......\....\.......\R$layout.class
......\...\.......\....\.......\R$string.class
......\...\.......\....\.......\R.class
......\...\.......\....\.......\SQLiteActivity$CreateListener.class
......\...\.......\....\.......\SQLiteActivity$InsertListener.class
......\...\.......\....\.......\SQLiteActivity$QueryListener.class
......\...\.......\....\.......\SQLiteActivity$UpdateListener.class
......\...\.......\....\.......\SQLiteActivity$UpdateRecordListener.class
......\...\.......\....\.......\SQLiteActivity.class
......\...\classes.dex
......\...\dexedLibs\annotations-228642ec9c33a1a0b73883a45604ffcd.jar
......\...\jarlist.cache
......\...\res\drawable-hdpi\icon.png
......\...\...\.........ldpi\icon.png
......\...\...\.........mdpi\icon.png
......\...\resources.ap_
......\...\sqlite.apk
......\gen\mars\sqlite3\BuildConfig.java
......\...\....\.......\R.java
......\project.properties
......\res\drawable-hdpi\icon.png
......\...\.........ldpi\icon.png
......\...\.........mdpi\icon.png
......\...\layout\main.xml
......\...\values\strings.xml
......\src\mars\sqlite3\db\DatabaseHelper.java
......\...\....\.......\SQLiteActivity.java
......\bin\classes\mars\sqlite3\db
......\...\.......\....\sqlite3
......\src\mars\sqlite3\db
......\bin\classes\mars
......\...\res\drawable-hdpi
......\...\...\drawable-ldpi
......\...\...\drawable-mdpi
......\gen\mars\sqlite3
......\src\mars\sqlite3
......\bin\classes
......\...\dexedLibs
......\...\res
......\gen\mars
......\res\drawable-hdpi
......\...\drawable-ldpi
......\...\drawable-mdpi
......\...\drawable-xhdpi
......\...\layout
......\...\values
......\src\mars
......\.settings
......\assets
......\bin
......\gen
......\res
......\src
sqlite追问
这是啥 = - 目录么..
Android中使用SQLite数据库
Android中使用SQLite数据库
目录标题
SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,它包含在一个相对小的C库中。它是D.RechardHipp建立的公有领域项目。它的设计目标是嵌入式的,而且已经在很多嵌入式产品中使用了它,它占用的资源非常的低,在嵌入式设备中,可能只需要几百k的内存就够了。它能够支持Window/Linux/Unix等等主流的操作系统,同时能够跟很多的程序语言相结合,比如Tcl、C#、PHP、Java等,还有ODBC接口,同样比起Mysql、PostgreSQL这两款开源的世界著名数据库来讲,它的处理速度比他们快。SQLite第一个Alpha版本诞生于2000年5月。至2021年已经接近有21个年头,SQLite也迎来了一个版本SQLite3已经发布。
1 SQLite和MySQL、Oracle等的区别
MySQL、Oracle这些数据库的数据是所有用户的数据,客户端通过服务器与数据库进行数据传递和交互。而SQLite这款轻量型数据库的数据是对应当前用户的数据,而且客户端也不用通过服务器与数据库进行数据传递和交互,相当于省去了服务器这一中介,从而使得处理速度快捷方便。
2 SQLite在Android Studio中的用法
2.1 第一种:利用工具类自动连接数据创建表
先创建一个工具类,然后在工具类中写入创建表和修改表的方法。
package com.huncm.sqlite;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
//工具类 自动连接数据 创建表
public class DBOpenHelper extends SQLiteOpenHelper
public DBOpenHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version)
super(context, name, factory, version);
@Override
public void onCreate(SQLiteDatabase db)
//创建表
String sql="create table user(id integer primary key autoincrement,username varchar(20),password varchar(20),age integer)";
db.execSQL(sql);
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
//修改表
对表的增删改查的四种方法:
1 增加数据
在MainActivity中,先对按钮设置点击事件,然后再写入以下调用方法。
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
//添加数据
DBOpenHelper mySQLiteHelper = new DBOpenHelper(MainActivity.this,"test",null,1);
SQLiteDatabase db = mySQLiteHelper.getWritableDatabase();
// hashmap(一个key,对应一个value)
ContentValues contentValues = new ContentValues();
contentValues.put("username","admin");
contentValues.put("password","111111");
contentValues.put("age",21);
db.insert("user",null,contentValues);
);
2 删除数据
在MainActivity中,先对按钮设置点击事件,然后再写入以下调用方法。
Button button2 = findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
//删除数据
DBOpenHelper mySQLiteHelper = new DBOpenHelper(MainActivity.this,"test",null,1);
SQLiteDatabase db = mySQLiteHelper.getWritableDatabase();
db.delete("user","id=? and username=?",new String[]"1","admin123");//用于删除指定的数据
);
3 查询数据
在MainActivity中,先对按钮设置点击事件,然后再写入以下调用方法。查询操作比较复杂,要用到cursor游标操作。
Button button3 = findViewById(R.id.button3);
button3.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
DBOpenHelper mySQLiteHelper = new DBOpenHelper(MainActivity.this,"test",null,1);
SQLiteDatabase db = mySQLiteHelper.getWritableDatabase();
//查询数据(利用游标实现)
Cursor cursor= db.query("user",null,"username=?",new String[]"admin123",null,null,null);
while (cursor.moveToNext())
String id = cursor.getString(cursor.getColumnIndex("id"));
String username = cursor.getString(cursor.getColumnIndex("username"));
int age = cursor.getInt(cursor.getColumnIndex("age"));
Log.i("Mainactivity", "result: id=" + id + " username: " + username + " age:" + age);
);
4 修改操作
在MainActivity中,先对按钮设置点击事件,然后再写入以下调用方法。
Button button4 = findViewById(R.id.button4);
button4.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
DBOpenHelper mySQLiteHelper = new DBOpenHelper(MainActivity.this,"test",null,1);
SQLiteDatabase db = mySQLiteHelper.getWritableDatabase();
ContentValues values2 = new ContentValues();
values2.put("username","小强");
db.update("user",values2,"username=?",new String[]"admin");
);
2.2 第二种:创建数据库操作类
先创建一个实体类,其中包含表中的那些属性,需要用到==@Entity==导入相关依赖包。这种方式更加简便,方便书写。
annotationProcessor 'androidx.room:room-compiler:2.2.5'
再创建一个数据库操作类,其中有抽象方法,是对表的增删改查。
package com.huncm.sqlite;
import androidx.room.Database;
import androidx.room.RoomDatabase;
@Database(entities = User.class,version = 1,exportSchema = false)
public abstract class UserDatabase extends RoomDatabase
public abstract UserDao getUserDao();
最后一个就是建立接口方法,去实现对表的增删改查。
package com.huncm.sqlite;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;
//建立接口方法
@Dao
public interface UserDao //数据库操作类 对表增删改查方法
@Insert
void insertUser(User...users);
@Delete
void deleteUser(User...users);
@Query("SELECT * FROM user")
List<User> findALLUser();
@Query("SELECT * from user Where id = :id")//条件查询
List<User> findAllUserByid(int id);
@Query("UPDATE user set username = :username Where id = :id")
void updateUser(String username,int id);
对表增删改查的四种方法:
先声明实例化类和方法,然后对表进行操作
UserDatabase userDatabase;
UserDao userDao;
userDatabase = Room.databaseBuilder(this,UserDatabase.class,"myuser").allowMainThreadQueries().build();
userDao = userDatabase.getUserDao();
1 增加数据
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
// 增加数据 -orm框架
User user = new User();
user.age = 23;
user.username = "小明";
user.password = "333333";
userDao.insertUser(user);
);
2 删除数据
Button button2 = findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
User user = new User();
user.id = 3;//用于删除指定的数据
userDao.deleteUser(user);
);
3 查询数据
Button button3 = findViewById(R.id.button3);
button3.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
List<User> userList = userDao.findALLUser();
for(User user : userList)
Log.i("MainActivity","userid = "+user.id+" name "+user.username);
)
4 更改操作
Button button4 = findViewById(R.id.button4);
button4.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
userDao.updateUser("小红",5);//更改id为5的username
);
总的MainAcitivity代码:
package com.huncm.sqlite;
import androidx.appcompat.app.AppCompatActivity;
import androidx.room.Room;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.util.List;
public class MainActivity extends AppCompatActivity
UserDatabase userDatabase;
UserDao userDao;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userDatabase = Room.databaseBuilder(this,UserDatabase.class,"myuser").allowMainThreadQueries().build();
userDao = userDatabase.getUserDao();
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
//添加数据
// DBOpenHelper mySQLiteHelper = new DBOpenHelper(MainActivity.this,"test",null,1);
// SQLiteDatabase db = mySQLiteHelper.getWritableDatabase();
// // hashmap(一个key,对应一个value)
// ContentValues contentValues = new ContentValues();
// contentValues.put("username","admin");
// contentValues.put("password","111111");
// contentValues.put("age",21);
// db.insert("user",null,contentValues);
// 增加数据 -orm框架
User user = new User();
user.age = 23;
user.username = "小明";
user.password = "333333";
userDao.insertUser(user);
);
Button button2 = findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
//删除数据
// DBOpenHelper mySQLiteHelper = new DBOpenHelper(MainActivity.this,"test",null,1);
// SQLiteDatabase db = mySQLiteHelper.getWritableDatabase();
// db.delete("user","id=? and username=?",new String[]"1","admin123");//用于删除指定的数据
User user = new User();
user.id = 3;//用于删除指定的数据
userDao.deleteUser(user);
);
Button button3 = findViewById(R.id.button3);
button3.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
// DBOpenHelper mySQLiteHelper = new DBOpenHelper(MainActivity.this,"test",null,1);
// SQLiteDatabase db = mySQLiteHelper.getWritableDatabase();
// //查询数据(利用游标实现)
// Cursor cursor= db.query("user",null,"username=?",new String[]"admin123",null,null,null);
// while (cursor.moveToNext())
// String id = cursor.getString(cursor.getColumnIndex("id"));
// String username = cursor.getString(cursor.getColumnIndex("username"));
// int age = cursor.getInt(cursor.getColumnIndex("age"));
// Log.i("Mainactivity", "result: id=" + id + " username: " + username + " age:" + age);
//
List<User> userList = userDao.findALLUser();
for(User user : userList)
Log.i("MainActivity","userid = "+user.id+" name "+user.username);
);
Button button4 = findViewById(R.id.button4);
button4.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
// DBOpenHelper mySQLiteHelper = new DBOpenHelper(MainActivity.this,"test",null,1);
// SQLiteDatabase db = mySQLiteHelper.getWritableDatabase();
// ContentValues values2 = new ContentValues();
// values2.put("username","小强");
// db.update("user",values2,"username=?",new String[]"admin");
userDao.updateUser("小红",5);
);
以上是关于关于android中使用SQLite数据库的查询基本操作.贴上代码.的主要内容,如果未能解决你的问题,请参考以下文章
使用 CursorLoader 查询 SQLite DB 并填充 AutoCompleteTextView
如何使用内容提供程序在 Sqlite 数据库中查询 Android 中的时间戳列?