简体   繁体   English

需要通过C#中的app.config文件连接数据库

[英]Need to connect database through app.config file in C#

I need to connect connect database through app.config file, stored procedure should get exceuted and the results should be stored in the datatable 我需要通过app.config文件连接连接数据库,存储过程应该被执行,并且结果应该存储在数据表中

App.config file: App.config文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
        <add name="Test" 
             connectionString="Data Source=servername; Initial Catalog=DBname; UserID=xx;password=xxx"    
             providerName="System.Data.SqlClient"/>
    </connectionStrings>
</configuration>

C# C#

SqlConnection DB = new SqlConnection(); 
DB.ConnectionString=ConfigurationManager.ConnectionStrings["Test"].ConnectionString;

SqlCommand cmd = new SqlCommand("[SP_active_user_profiles]", DB); 
cmd.CommandType = CommandType.StoredProcedure;  

DataTable dt = new DataTable();  

SqlDataAdapter adapter = new SqlDataAdapter(cmd); 

adapter.Fill(dt);

My problem is: I could n't connect to database itself, it throws null reference exception and the stored procedure results to be stored in the datatable. 我的问题是:我无法连接到数据库本身,它会引发空引用异常,并且存储过程的结果将存储在数据表中。

where is my mistake? 我的错误在哪里?

use it like this: 像这样使用它:

private string connectionString = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;

public void YourMethod()
{
   DataTable table = null;
   try
   {
       using (SqlConnection connection = new SqlConnection(this.connectionString))
       {
           connection.Open();
           SqlCommand cmd = connection.CreateCommand();

           cmd.CommandText = "SP_active_user_profiles";
           cmd.CommandType = CommandType.StoredProcedure;

           using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
           {
               table = new DataTable();
               adapter.Fill(table);
           }
       }

   }
   catch (Exception ex)
   {
       //Handle your exeption
   }
}

连接字符串应如下所示: <add name="Test" connectionString="Data Source=servername;Initial Catalog=DBname; User ID=xx;Password=xxx;Integrated Security=SSPI; " providerName="System.Data.SqlClient"/>

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

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