简体   繁体   English

连接到app.config中的connectionString

[英]Connecting to connectionString in app.config

I have my connection string stored in App.Config 我的连接字符串存储在App.Config中

<connectionStrings>
 <clear />
 <add name="CTaC_Information_System.Properties.Settings.CIS_beConn"
     connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=&quot;\\server\file\CIS Data\Database\CIS_be.accdb&quote;;Jet OLEDB:Database Password=123" 
     providerName="System.Data.OleDb" />

Then when I go to my main.xaml.cs I type in the following: 然后,当我转到main.xaml.cs时,请输入以下内容:

string cisconn = ConfigurationManager.ConnectionStrings["CTaC_Information_System.Properties.Settings.CIS_beConn"].ConnectionString;`

I found that answer on Stack Overflow when searching, but some were say to put var but when I typed var it wouldn't recognize it so I went with the string method. 我在搜索时在Stack Overflow上找到了该答案,但有人说放var但是当我键入var它无法识别,所以我使用了string方法。

When I go to type cisconn.Open(); 当我输入cisconn.Open(); the option isn't there. 该选项不存在。 I am referencing System.Configuartion; 我正在引用System.Configuartion; , System.Data.Sql; System.Data.Sql; System.Data.SqlClient; and System.Data.OleDb; System.Data.OleDb; .

Can someone show / tell me how I can connect to the database from c#? 有人可以显示/告诉我如何从c#连接到数据库吗? I'm trying to test the connection when my application runs but I can't figure it out. 我正在尝试在应用程序运行时测试连接,但无法弄清楚。

The connection string is just a string, its meant to be used in your connection, so you should do: 连接字符串只是一个字符串,它应在您的连接中使用,因此您应该执行以下操作:

public void DoSomeDatabaseOp()
{
    string cisconn = ConfigurationManager.ConnectionStrings["CTaC_Information_System.Properties.Settings.CIS_beConn"].ConnectionString;

    using (OleDbConnection conn = new OleDbConnection(cisconn))
    {
        conn.Open();
        //Create your commands or do your SQL here.
    }
}

You should create/destroy the connection inside the method you are using it in. Don't keep a reference to it in the root of the class object. 您应该在使用该方法的方法内部创建/销毁该连接。不要在类对象的根目录中保留对它的引用。 This keeps the connections clean and open if you aren't doing database operations. 如果您不执行数据库操作,则可以保持连接的清洁和开放。

If you really wanted to though, you could do this: 如果您确实想这样做,则可以执行以下操作:

class MyClass
{
    OleDbConnection _rootConn;
    string _connStr;

    public MyClass()
    {
        _connStr = string cisconn = ConfigurationManager.ConnectionStrings["CTaC_Information_System.Properties.Settings.CIS_beConn"].ConnectionString;
        _rootConn = new OleDbConnection(_connStr);
    }

    public void DoSomeDatabaseOp()
    {
        //Use _rootConn here
    }
}

BUT the class should implement IDisposable so that it can dispose of the connection properly! 但是该类应该实现IDisposable,以便它可以正确处理连接! How to implement IDisposable is beyond the scope of the answer, but look up how to implement it properly. 如何实现IDisposable超出了答案的范围,但是请查找如何正确实现它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM