Learn more about Dart tutorials and technical articles.

Introduction to the

This article will learn how to set up a configuration file to connect to a PostgreSQL database

1. Add a configuration file

We can in the main. Find the option in the dart. ConfigurationFilePath, its value corresponding to the configuration file path, the default project as root

1import 'package:demo/demo.dart'; 2 3Future main() async { 4 final app = Application<DemoChannel>() 5//watch 6 .. Options. ConfigurationFilePath = "config. Yaml" / / load the configuration file 7 / / watch 8.. options.port = 8888; / / the port number 910 final count = Platform. The numberOfProcessors ~ / 2; F // IP phone number 11 await app.start(numberOfInstances: count > 0? count : 1); ${app.options.port}." print("Application started on port: ${app.options.port}."); 14 print("Use Ctrl-C (SIGINT) to stop running the application."); 15}Copy the code

You can see that the configuration file is config.yaml under the project folder

1port: 8080Copy the code

Set our port number to 8080 and create a new AppConfig class under the lib folder as follows:

1import 'demo.dart'; 23class AppConfig extends Configuration{45 AppConfig(String path):super.fromFile(File(path)); 67 int port; 89}Copy the code

Dart file to apply your configuration to the project

1class DemoChannel extends ApplicationChannel {2 @override3 Future prepare() async {4//new5 final AppConfig _config=AppConfig(options.configurationFilePath); 6 options.port=_config.port; 7//new8 }9}Copy the code

Then start your server

bug
Port: 8888
8080
8888

2. The PostgreSQL database

PostgreSQL = PostgreSQL = PostgreSQL = PostgreSQL = PostgreSQL = PostgreSQL = PostgreSQL = PostgreSQL = PostgreSQL = PostgreSQL = PostgreSQL = PostgreSQL = PostgreSQL = PostgreSQL = PostgreSQL = PostgreSQL = PostgreSQL = PostgreSQL

PostgreSQL is introduced

  • PostgreSQL is a free object-relational database server (database management system) distributed under a BSD license. — Wikipedia

  • The World’s Most Advanced Open Source Relational Database

  • Can find the answer on zhihu on https://www.zhihu.com/question/20010554

PostgreSQl installed

Open the website https://www.postgresql.org/ click on the Download, find your system corresponding to the version, I am corresponding macos

Download the installer


brew

1brew install postgresqlCopy the code

After the installation is complete, go to /usr/local/var/postgres

PostgreSQl initialization

  • Check the current version pg_ctl -v

1rhymes-MacBook-Air:~ rhyme$ pg_ctl -V2pg_ctl (PostgreSQL) 11.5Copy the code
  • Brew Services start PostgresQL

1rhymes-MacBook-Air:~ rhyme$ brew services start postgresql2==> Successfully started `postgresql` (label: homebrew.mxcl.postgresql)Copy the code
  • Brew Uninstall Postgres

  • Add user createUser –interactive

1rhymes-MacBook-Air:~ rhyme$ createuser --interactive2Enter name of role to add: rhymelph3Shall the new role be a superuser? (y/n) yCopy the code
  • Change the password

1rhymes-MacBook-Air:~ rhyme$PSQL postgres2pSQL (11.5)3Type "help" for help.4postgres=# \password rhymelph5Enter new password: 6Enter it again:Copy the code

Use Navicat Premium, a database visualization tool

  • Create a New connection

  • Creating a Database

Ok, we have the account, password, database, now let’s connect the project to the database

3. Connect the project to the database

  • Add in the config.yaml file

1database:2  host: localhost3  port: 54324  databaseName: "my_data"5  username: "rhymelph"6  password: "123456"Copy the code
  • Add the following code to the app_config.dart file

1import 'demo.dart'; 23class AppConfig extends Configuration{4 AppConfig(String path):super.fromFile(File(path)); 5 int port; 6//new7 DatabaseConfiguration database; 8//new9}Copy the code
  • Generate the instance in the channel.dart folder

1class DemoChannel extends ApplicationChannel { 2 ManagedContext context; 3 4 @override 5 Future Prepare () async {6 // Method for performing the initialization task 7 Final AppConfig _config = AppConfig(options.configurationFilePath); 8 options.port = _config.port; 9//new10 final dataModel = ManagedDataModel.fromCurrentMirrorSystem(); / / describe the application's data model and final PSC. = PostgreSQLPersistentStore fromConnectionInfo (12 _config. Database. The username, 13 _config.database.password,14 _config.database.host,15 _config.database.port,16 _config.database.databaseName); 17 Context =ManagedContext(dataModel, PSC); 18//new19 }20}Copy the code

At this point, we are ready to use the database, but Aqueduct provides us with the ability to map entity classes to tables

4. Map entity classes to tables

  • Run the aqueduct db generate command to initialize the migration file. After running the command, a version migration file will be generated in the project

  • Run the command aqueduct db upgrade – connect postgres: / / rhymelph: 123456 @ localhost: 5432 / my_data moving version file synchronization to your database

  • You can also create a database.yaml file in the root directory of your project and store the database information. Next time, just run aqueduct DB upgrade

1username: "rhymelph"2password: "123456"3host: "localhost"4port: 54325databaseName: "my_data"Copy the code
  • Create a new Article class and add the following

1import '.. /demo.dart'; 2 3Class Article extends ManagedObject<_Article> implements _Article {} 4 5class _Article {6 @primaryKey == @7 int id; 8 9 String content; // Contents 1011 @column (indexed: true)// Add index 12 DateTime createData; 13}Copy the code

Aqueduct db generate and Aqueduct DB Upgrade can then be used to synchronize the entity class fields to the database (note that the entity class must be imported into channel.dart to be valid)

Aqueduct

5. Use the interface to query the database

Next we add a piece of data to the table and add the following code to channel.dart

1 @override 2 Controller get entryPoint {3 // Define routes, request links, etc., call 4 during startup... 5//new 6 router.route('/queryAllArticle').linkFunction((request) async{ 7 final query = Query<Article>(context); 8 Final List<Article> articles=await query.fetch(); 9 return response. ok(articles); // Data is returned to the client as json 10}); 11//new12 return router; 13}Copy the code

As you can see, the Aqueduct using ORM object relational mapping, dispense with the trouble that use SQL statements, is very convenient, then we can start the server, http://localhost:8080/queryAllArticle access interface

When you see that the request was successful and the data we stored in the database is displayed, 👏 congratulations, you successfully used the interface to query the database! This section of learning is over here, I hope to help forward, so that more partners learn this language and framework