C# 在C应用程序中添加数据库服务器信息
我在c应用程序中使用以下连接字符串与本地托管的数据库通信C# 在C应用程序中添加数据库服务器信息,c#,postgresql,c#-4.0,desktop-application,C#,Postgresql,C# 4.0,Desktop Application,我在c应用程序中使用以下连接字符串与本地托管的数据库通信 string conn = String.Format("Server={0};Port={1};" + "User Id={2};Password={3};Database={4};", "localhost", "5432", "postgres",
string conn = String.Format("Server={0};Port={1};" +
"User Id={2};Password={3};Database={4};",
"localhost", "5432", "postgres",
"postgres", "table");
NpgsqlConnection connection = new NpgsqlConnection(connstring);
connection.Open();
NpgsqlCommand sqlcmd = new NpgsqlCommand("SELECT * FROM public.roads", connection);
NpgsqlDataReader r = sqlcmd.ExecuteReader();
有什么方法可以在config.app文件中添加服务器信息并在代码中访问它吗?签出
在app/web.config中:
<configuration>
<configSections>
(...)
<connectionStrings>
<add name="Name1" connectionString="..." />
</connectionStrings>
请注意,使用ConnectionString部分而不是appSettings的好处是,如果您使用的是对象关系映射框架,则可能支持按名称使用连接字符串
e、 g
先前看到的链接可能重复,但无法将其与我的问题关联。是,请在app.config或web.config文件中添加该链接。并通过配置访问它manager@BhubanShrestha谢谢你的评论。你能给我提供一个链接或任何与此相关的资源吗。我是c开发的新手。您需要添加对configuration manager的引用,以访问配置文件中的连接字符串。您必须在start中添加{using System.configuration;},这就像一个符咒。
var connectionString = ConfigurationManager.ConnectionStrings["Name1"].ConnectionString;
public class RepositoryContext: DbContext
{
public RepositoryContext() : base("Name1")
{
(...)
}