-1

我在执行非查询时得到这个..调用 ExecuteNonQuery....

   clsConnection.ExecuteNonQuery("ADD_CUSTOMERS", CommandType.StoredProcedure, paramList);

异常弹出在cmd.Connection.Open();

这是整个 ExecuteNonQuery

 public static void ExecuteNonQuery(string sql, CommandType type, List<SqlParameter> paramList)




        try
        {
            DataAccess.clsConnection clsDB = new DataAccess.clsConnection();
            using (SqlConnection cn =clsDB.OpenCon())
            {
                SqlCommand cmd = new SqlCommand();
                cmd = CreateCommand(sql, type, paramList);
                cmd.Connection = cn;
                cmd.CommandType = type;
                cmd.CommandText = sql;
                cmd.ExecuteNonQuery();


            }  
4

4 回答 4

3

您没有将连接对象分配给命令

当 SqlCommand 执行查询时,它需要一个打开的连接。所以第一步是搜索它的连接属性,看它是否已经初始化。该属性为空,因此您会收到错误

只需修复它

 cmd.Connection = MainCon;

当然,您已经打开了连接,因此您不需要该线路

 cmd.Connection.Open();

话虽如此,我真的建议您避免以这种方式保留全局连接对象。更改OpenCon以返回打开的连接并在不再需要时使用 using 语句释放资源,这对性能和对程序使用的系统资源的影响会更好

namespace DataAccess
{
    public class clsConnection
    {
        public SqlConnection OpenCon()
        {           
                DBN = "PMS";
                SERVER = "server-PC\\SQLEXPRESS";
                USER = "SA";
                PWD = "Sysadmin123";

                SqlConnection cn = new SqlConnection("Initial Catalog=" + DBN + ";Data Source=" + SERVER + "; User id =" + USER + "; Password =" + PWD + ";CONNECT Timeout=10");
                .....
                cn.Open();                   
                return cn;

        }        

    }
}

因此,您使用连接的代码可以更改为

try
{
   DataAccess.clsConnection clsDB = new DataAccess.clsConnection();
   using(SqlConnection cn = clsDB.OpenCon())
   {
       SqlCommand cmd = new SqlCommand();
       cmd = CreateCommand(sql, type, paramList);
       cmd.Connection = cn;
       cmd.CommandType = type;
       cmd.CommandText = sql;
       cmd.ExecuteNonQuery();

    // Here the closing braces closes and disposes the connection freeing the resources used
    // also in case of exceptions 
    }  
}
catch (Exception ex)
{
    ....
}

编辑:在下面看到您的评论,为 OpenCon 方法添加了更多上下文。我强烈建议您更改代码并利用using 语句

于 2013-07-31T13:19:18.327 回答
2

您必须将连接分配给命令

cmd = CreateCommand(sql, type, paramList);
cmd.Connection = MainCon;
于 2013-07-31T13:19:00.163 回答
1

使用Connection Timeout代替Connect Timeout

于 2013-07-31T13:18:24.067 回答
0

我建议使用 SqlConnectionStringBuilder!

var builder = new SqlConnectionStringBuilder();
builder.DataSource = "server-PC\\SQLEXPRESS";
builder.InitialCatalog = "PMS";
builder.UserID = "SA";
builder.Password = "Sysadmin123";

using (var connection = new SqlConnection(builder.ToString()))
{
    using (var cmd = new SqlCommand())
    {
        cmd.CommandText = "ADD_CUSTOMERS";
        cmd.CommandType = System.Data.CommandType.StoredProcedure;
        cmd.Connection = connection;

        connection.Open();
        cmd.ExecuteNonQuery();
        connection.Close();
    }
}
于 2013-07-31T13:23:09.363 回答