您的位置:首页 > 编程语言 > ASP

ASP .NET错误信息:"/"应用程序中的服务器错误。列"uaddrgt"不属于表Table 的一个原因及解决办法

2010-12-13 10:55 811 查看
我们一个客户的代码,经常发生如 ASP .NET错误信息:"/"应用程序中的服务器错误。列"uaddrgt"不属于表Table

这一类的错误,仔细查看代码,发现下面的问题:

下面的代码是负责创建数据库连接,同时打开或者不打开数据库事务(下面的代码是客户的错误代码)。

namespace haierp.DataAccessLayer
{
public sealed class SqlHelper
{
private static SqlConnection conn = null;
private static SqlCommand command = null;
private static SqlTransaction tran = null;


public static SqlCommand GetCommand(string connectstr)
{
conn = new SqlConnection(connectstr);
conn.Open();
command = conn.CreateCommand();
command.CommandTimeout = 60000;
return command;
}

public static bool EndCommand()
{
bool state = false;
try
{

command.Connection.Close();
state = true;
}
catch
{
state = false;
conn.Close();
}
return state;
}

public static bool SqlCommit(SqlCommand command)
{
bool state = false;
try
{
command.Transaction.Commit();
state = true;
}
catch
{
state = false;
}
finally
{
command.Connection.Close();
command.Connection = null;
command = null;
}
return state;
}

public static bool SqlRollback(SqlCommand command)
{
bool state = false;
try
{
command.Transaction.Rollback();
state = true;
}
catch
{
state = false;
}
finally
{
command.Connection.Close();
command.Connection = null;
command = null;
}
return state;
}
}
}

由于这是用于ASP .NET的共用代码,因此存在多个客户并发访问的问题,同时由于使用了上面红色标注的静态

私有变量,因此多个客户ASP线程是共享SqlConnection,SqlCommand,SqlTransaction,于是一个线程

生成的conn,就可能被别的线程关闭,一个线程生成的Transaction,就可能被别的线程提交或者回滚。

正确的做法是:取消使用这里的静态私有变量,采用动态对象,或者函数参数的形式,以保证各线程使用自己私有的

SqlConnection,SqlCommand,SqlTransaction对象,避免彼此干扰。如下所示是正确的代码:

namespace haierp.DataAccessLayer
{

public sealed class SqlHelper
{

//private static SqlConnection conn = null;
//private static SqlCommand command = null;
//private static SqlTransaction tran = null;


public static SqlCommand GetCommand(string connectstr)
{
SqlConnection conn = new SqlConnection(connectstr);
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandTimeout = 60000;
return command;
}

public static SqlCommand GetTranCommand(string connectionString)
{
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand command = conn.CreateCommand();
SqlTransaction tran = conn.BeginTransaction();
command.Transaction = tran;
command.CommandTimeout = 60000;

return command;
}

public static void EndCommand(SqlCommand command)
{
if (command.Connection.State == ConnectionState.Open)
{
command.Connection.Close();
}
}

public static void SqlCommit(SqlCommand command)
{
command.Transaction.Commit();
if (command.Connection.State == ConnectionState.Open)
{
command.Connection.Close();
}
}

public static void SqlRollback(SqlCommand command)
{
command.Transaction.Rollback();
if (command.Connection.State == ConnectionState.Open)
{
command.Connection.Close();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐