两种没有什么区别,但最好try{}catch{}finally{}包含起来..

解决方案 »

  1.   

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
    using (SqlCommand cmd = new SqlCommand(SQLString,connection))
    {
    try
    {
    connection.Open();
    int rows=cmd.ExecuteNonQuery();
    return rows;
    }
    catch(System.Data.SqlClient.SqlException E)
    {
    connection.Close();
    throw new Exception(E.Message);
    }
    finally
    {
                            connection.Close();
    }
    }
    }
      

  2.   

    ========
    第一种 
    SQLConnection Conn= new SqlConnection();
    Conn.Open();
    SqlCommand  cmd=new SqlCommand();
    cmd.ExcuteQuery();
    Conn.Close();===================很明显 有问题 : cmd 没有与 Conn 关联起来..,Conn 没有打开
    楼主 应该表达的是  通过 SQL 字符串来执行操作..
    要么跟第二中一样用cmd.Connection=Conn;
    cmd.CommandText=query;
    要么用  SqlCommand  cmd=new SqlCommand(Conn,query);
    ==
    第二种
    SqlCommand sqlCmd = new SqlCommand();
    sqlCmd.Connection = DataQuery.GetNewSqlConnection(); ====Conn
    sqlCmd.CommandText = query; ===代表SQL 字符串
    sqlCmd.CommandType = CommandType.Text;=======他有3个参数,默认就是这个
    if(sqlCmd.Connection.State == System.Data.ConnectionState.Closed)
    sqlCmd.Connection.Open();
    intResult = sqlCmd.ExecuteNonQuery();
    sqlCmd.Connection.Close();
    sqlCmd.Dispose();
    sqlCmd = null;
    =========================================
      

  3.   

    SQLConnection Conn= new SqlConnection("-------------");
    Conn.Open();
    SqlCommand  cmd=new SqlCommand("--------------",Conn);
    cmd.ExcuteQuery();===================================此步之前应该还有别的语句
    Conn.Close();第二种很少人这样写的吧