2

我尝试了以下代码,但我无法从中找到成功消息。这里commandText可以是插入、更新、删除或选择查询,如果它是一个选择查询,我需要数据集,否则像 sql 结果中的成功消息output("12 row(s) inserted successfully")。我不能使用ExecuteScalarExecuteNonQuery方法,因为在执行选择查询时我需要数据集输出。

public static  DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
    {
        using (SqlConnection cn = new SqlConnection(connectionString))
        {
            cn.InfoMessage += delegate(object sender, SqlInfoMessageEventArgs e)
            {
                MessageInfo += "\n" + e.Message;
            };
            cn.FireInfoMessageEventOnUserErrors = true;

            cn.Open();
            using (SqlCommand command = new SqlCommand(commandText, cn))
            {

                using (SqlDataAdapter adapter = new SqlDataAdapter(command))
                {
                    DataSet dt = new DataSet();
                    adapter.Fill(dt); // Do something with DataTable
                    return dt;
                }
            }
        }
    }
4

2 回答 2

1

我正在使用 System.Data 版本 4.0.0.0,以下适用于我的 UPDATE、INSERT、DELETE 和 SELECT 语句。

using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
    var rowsAffected = -1;

    adapter.SelectCommand.StatementCompleted += delegate (object sender, StatementCompletedEventArgs e)
    {
        rowsAffected = e.RecordCount;
    };

    DataSet dt = new DataSet();
    adapter.Fill(dt); // Do something with DataTable
    return dt;
}
于 2015-12-31T18:07:22.750 回答
0

我设法通过以下方式解决了它,但希望应该有更好的方法。

 string type = Query.Trim().Split(' ')[0].ToLower();
    if ( type == "select")
    {
        DataSet result = SqlHelper.ExecuteDataset(CommandType.Text, Query);                

    }
    else
    {                
        if(type == "insert") type="inserted."; else type=type+"d.";
        int a=(int)SqlHelper.ExecuteNonQuery(CommandType.Text, Query);
        if (a > 0)
        {
            lblInfo.Text = "Query executed successfully. " + a.ToString() + " row(s) " + type;                

        }
    }

我又找到了一个,比上面那个好。

query = resultQuery + "  SELECT '('+CONVERT(VARCHAR(10),@@ROWCOUNT)+' row(s) affected)' AS RESULT";
DataSet result = DataSet result = SqlHelper.ExecuteDataset(CommandType.Text, query);

        if (result.DefaultViewManager.DataViewSettingCollectionString.Contains("Table") == true)
        {
            sqlGrid.Visible = true;
            sqlGrid.DataSource = result;
            sqlGrid.DataBind();
        }
        if (sqlGrid.Rows.Count==1 && sqlGrid.Rows[0].Cells.Count==1)
        {
            string text = (sqlGrid.Rows[0].Cells[0]).Text;
            if (text.Contains("row(s) affected"))
            {
                lblInfo.Text=text;
                lblInfo.Visible=true;
                sqlGrid.DataSource = null;
                sqlGrid.DataBind();
            }
        }
于 2012-07-07T13:02:53.923 回答