2016-10-28 36 views
0

我需要连接数据库通过app.config文件连接,存储过程应该得到exceuted连接数据库和结果应存储在数据表需要通过app.config文件在C#中

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#

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); 

我的问题是:我不能连接到ct到数据库本身,它会抛出空引用异常,并将存储过程结果存储在数据表中。

我的错误在哪里?

+0

有什么问题吗? – Gareth

+0

好的,问题是? – mybirthname

+0

我无法连接到数据库本身,它会引发空引用异常,并将存储过程结果存储在数据表中。 –

回答

1

使用这样的:

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 
    } 
} 
+0

尽管我使用这个try catch方法.still我得到的Nullreference异常在调试时未处理,我坚持上面的代码的第一行,我不能移动进一步的调试 –

+0

什么是异常消息? – SeM

+0

对不起,在我的appconfig文件中出现错误。你的代码工作完美..Tq。 –

1

连接字符串应该是这样的<add name="Test" connectionString="Data Source=servername;Initial Catalog=DBname; User ID=xx;Password=xxx;Integrated Security=SSPI; " providerName="System.Data.SqlClient"/>