如何在 Flutter 中使用 SQFlite 进行数据库查询
问题描述
如何使用 SQFlite 插件在 Flutter 中查询 SQLite 数据库中的数据?
我最近一直在努力学习这个,所以我在下面添加我的答案,作为帮助我学习的一种方式,也作为未来其他人的快速参考.
添加依赖项
打开 pubspec.yaml
并在依赖项部分添加以下行:
sqflite
当然是
为了方便您复制和粘贴,这里是 main.dart
的布局代码:
继续
- 这篇文章是我之前文章的发展:SimpleFlutter 中的 SQFlite 数据库示例.有关其他 SQL 操作和建议,请参阅该博文.
How do you query data from SQLite database in Flutter using the SQFlite plugin?
I have been working on learning this recently, so I am adding my answer below as a means to help me learn and also as a quick reference for others in the future.
Add the dependencies
Open pubspec.yaml
and in the dependencies section add the following lines:
The sqflite
is the SQFlite plugin of course and the path_provider
will help us get the user directory on Android and iPhone. You can check the most up-to-date version numbers here: sqflite and path_provider.
Make a database helper class
I'm keeping a global reference to the database in a singleton class. This will prevent concurrency issues and data leaks. You can also add helper methods (like query) in here for accessing the database.
Create a new file called database_helper.dart and paste in the following code:
Note that when the database is created I pre-populated a few rows. This is so that we have something to work with in the query examples below.
Query data
We'll use an async method to do our query because database operations can be expensive.
Getallrows
To do a SELECT *
and return everything in the table you just pass in the table name.
Getasinglerow
We can pass an argument in for the where
parameter to select specific rows that meet our criteria. In this example we will query the row with an ID of 1
.
The items in the whereArguments
list get substituted in place of the ?
s in the whereString
. In this case there was only one ?
so the whereArguments
only had one item. If there were two ?
s (for example an integer and a string), then you would have two items in the list.
Rawquery
If you prefer the familiarity or flexibility of SQL code itself, you can do a raw query. In this example we will select any row whose name
column is 'Mary'
.
Be sure to use data binding using ?
string replacements. This will guard against SQL injection attacks.
Notes
- You will have to import the
DatabaseHelper
class andsqflite
if you are in another file (like main.dart). - The SQFlite plugin uses a
Map<String, dynamic>
to map the column names to the data in each row.
Supplemental code
For your copy-and-paste convenience, here is the layout code for main.dart
:
Going on
- This post is a development from my previous post: Simple SQFlite database example in Flutter. See that post for other SQL operations and advice.
这篇关于如何在 Flutter 中使用 SQFlite 进行数据库查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!