无法创建连接字符串

时间:2010-09-18 04:19:27

标签: sql-server ado.net database-connection

我正在开发一个网站,我无法创建连接字符串,我已经包含了所有必需的命名空间,但是当我创建一个字符串变量来存储连接时,它不会声明SqlConnection对象,但我能够在构造函数类中创建连接字符串,为什么我无法在构造函数外部创建连接。有什么特别的原因..

1 个答案:

答案 0 :(得分:0)

App.config中:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="main" providerName="System.Data.SqlClient" connectionString="Data     Source=localhost;Initial Catalog=mydatabase;User Id=myid;Password=mypassword;"/>
  </connectionStrings>
<configuration>

C#代码:

using System.Configuration;

public string _connectionString = ConfigurationManager.ConnectionStrings[1].ConnectionString;

public string GetString(string sql, SqlParameter[] parameters)
{
  List<string> result = new List<string>();
  SqlDataReader reader;
  using (SqlConnection connection = new SqlConnection(_connectionString ))
  {
    SqlCommand command = new SqlCommand(sql, connection);
    if (parameters != null)
    {
      command.Parameters.Clear();
      command.Parameters.AddRange(parameters);
    }
    connection.Open();
    reader = command.ExecuteReader();
    while (reader.Read())
    {
      string row = string.Empty;
      foreach (string col in reader)
      {
        row += col + ",";
      }
      result.Add(row)
    }
    reader.Close();
  }
  return result;
}