c#DB相关错误
本文关键字:错误 c#DB | 更新日期: 2023-09-27 18:26:49
这里是连接字符串:
<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>
这是代码背后:
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:
这个序列会杀死你:
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();
}
}
您应该使用WebConfigurationManager
而不是ConfigurationManager
来读取web.config
文件。
操作方法在MSDN上,只涉及在您的案例中替换类的名称。