编程实践:在SqlDataAdapter中使用ExecuteNonQuery

dee*_*pti 0 c#

 public DataTable UserUpdateTempSettings(int install_id, int install_map_id, string Setting_value,string LogFile)
    {

        SqlConnection oConnection = new SqlConnection(sConnectionString);
        DataSet oDataset = new DataSet();
        DataTable oDatatable = new DataTable();
        SqlDataAdapter MyDataAdapter = new SqlDataAdapter();

        try
        {
            oConnection.Open();
            cmd = new SqlCommand("SP_HOTDOC_PRINTTEMPLATE_PERMISSION", oConnection);            
            cmd.Parameters.Add(new SqlParameter ("@INSTALL_ID", install_id));
            cmd.Parameters.Add(new SqlParameter ("@INSTALL_MAP_ID", install_map_id));
            cmd.Parameters.Add(new SqlParameter("@SETTING_VALUE", Setting_value));
            if (LogFile != "")
            {
                cmd.Parameters.Add(new SqlParameter("@LOGFILE",LogFile));
            }
           cmd.CommandType = CommandType.StoredProcedure;
           MyDataAdapter.SelectCommand = cmd;
           cmd.ExecuteNonQuery();                    
           MyDataAdapter.Fill(oDataset);
           oDatatable = oDataset.Tables[0];
           return oDatatable;
        }
        catch (Exception ex)
        {
            Utils.ShowError(ex.Message);
            return oDatatable;
        }
        finally
        {
            if ((oConnection.State != ConnectionState.Closed) || (oConnection.State != ConnectionState.Broken))
            {
                oConnection.Close();
            }

            oDataset = null;
            oDatatable = null;
            oConnection.Dispose();
            oConnection = null;
        }
    }
Run Code Online (Sandbox Code Playgroud)

ExecuteNonQuery上面用过.通常它不会与之一起使用SqlDataAdapter.如果我不使用它,我会收到错误.

它是坏的编程习惯使用ExecuteNonQuerySqlDataAdapter

MUG*_*G4N 6

嗨deepti你不必调用executeNonQuery,因为dataadapter的fill方法正在照顾你.这是一个小样本:

    using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsFormsApplication9
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            FillData();
        }

        void FillData()
        {
            // 1
            // Open connection
            using (SqlConnection c = new SqlConnection(
                Properties.Settings.Default.DataConnectionString))
            // 2
            // Create new DataAdapter
            using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM EmployeeIDs", c))
            {
                // 3
                // Use DataAdapter to fill DataTable
                DataTable t = new DataTable();
                a.Fill(t);

                // 4
                // Render data onto the screen
                // dataGridView1.DataSource = t; // <-- From your designer
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 也无需在代码中打开连接--Fill()方法也会为您执行此操作. (2认同)