c#DB相关错误

时间:2014-10-16 13:23:37

标签: c# sql asp.net sql-server

这是连接字符串:

<connectionStrings>
    <add name="DBConnection" connectionString="Data Source=Personal-PC;Initial Catalog=LocalDB;Persist Security Info=True;User ID=google;Password=google" providerName="System.Data.SqlClient" />
</connectionStrings>

这是Code Behind:

public string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ToString();

public void ExecuteSQL(string sqlstring, List<SqlParameter> sqlparam)
{
    try
    {
        SqlConnection objsqlconn = new SqlConnection();
        objsqlconn.ConnectionString = connectionString;
        if (objsqlconn.State != ConnectionState.Open)
        {
            objsqlconn.Close();
            objsqlconn.Dispose();
            objsqlconn.Open();
        }

        SqlCommand objcmd = new SqlCommand(sqlstring, objsqlconn);
        int i, cnt = sqlparam.Count();

        for (i = 0; i < cnt; i++)
            objcmd.Parameters.Add(sqlparam[i]);
        objcmd.ExecuteNonQuery();
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
}

我得到以下错误。当我尝试将数据插入sql表时。实际上是什么意思以及如何解决这个错误。

System.InvalidOperationException was caught
  HResult=-2146233079
  Message=The ConnectionString property has not been initialized.
  Source=System.Data
  StackTrace:
       at System.Data.SqlClient.SqlConnection.PermissionDemand()
       at System.Data.SqlClient.SqlConnectionFactory.PermissionDemand(DbConnection outerConnection)
       at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
       at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
       at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
       at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
       at System.Data.SqlClient.SqlConnection.Open()
       at DBdml.DBACC.InsertUpdateDeleteSQLString(String sqlstring, List`1 sqlparam) in D:\dotnet\ASP.netC#\BusinessLayer\DBACC.cs:line 78
  InnerException: 

2 个答案:

答案 0 :(得分:2)

这个序列会杀了你:

objsqlconn.Close();
objsqlconn.Dispose();
objsqlconn.Open();

处理完毕后,您无法使用连接对象。真的,你可以大大简化整个方法:

public void ExecuteSQL(string sqlstring, IEnumerable<SqlParameter> sqlparam)
{
    using (SqlConnection cn = new SqlConnection(connectionString))
    using (SqlCommand cmd = new SqlCommand(sqlstring, objsqlconn))
    {
        cmd.Parameters.AddRange(sqlparam.ToArray());
        cn.Open();
        cmd.ExecuteNonQuery();
    }
}

答案 1 :(得分:0)

您应该使用WebConfigurationManager代替ConfigurationManager来阅读web.config文件。

操作方法是here on MSDN,只需要在您的案例中替换类的名称。