Table of contents
Get configuration connection database
Use Visual Studio
Right-click on the class that needs to add a configuration file - Add - New Item
Select the application configuration file, note that the name has format requirements
If you use vs to generate, there is an initialization code, and then there is a prompt when you enter it
Use Rider
Right-click the project that needs to add a configuration file, Add - File
If you use Rider, there is no content prompt
<?xml version = "1.0" encoding = "UTF-8" ?>
<configuration>
<connectionStrings>
<!-- 本地数据库连接字符串 -->
<add name="localString" connectionString="Host=localhost;Port=5432;Username=postgres;Password=1qazZAQ!;Database=study"/>
<!-- 远程数据库连接字符串 -->
<add name="devString" connectionString="Host=139.124.133.132;Port=1921;Username=postgres;Password=1qazZAQ!;Database=study"/>
</connectionStrings>
</configuration>
Install Nuget package
ConfigurationManager
Get configuration connection database
using System.Configuration;
using System.Data;
using Npgsql;
//获取配置文件中名为“localString”的 ConnectionStrings
var connectionString = ConfigurationManager.ConnectionStrings["localString"].ConnectionString;
//创建连接,使用上面获取的值配置
using NpgsqlConnection conn = new NpgsqlConnection(connectionString);
//创建DataAdapter数据适配器,使用查询语句
using var npgsqlDataAdapter = new NpgsqlDataAdapter("select * from user1", conn);
DataTable dataTable = new DataTable();
//使用 npgsqlDataAdapter.Fill 方法将数据填充到 DataTable
npgsqlDataAdapter.Fill(dataTable);
Make a breakpoint and use debug to get the inverted data
The above demonstrates how to read the content of the configuration file to connect to the database. For other database operations and connection methods, please refer to the blog: C# uses Npgsql or SqlClient to connect to the database