先看看我的SQL2005存储过程:
create procedure sp_test
AS
SELECT * FROM Renter
//截图如下
------------------------------------------------------------------------------------------------------------------------------------------------
在C#中我们如何通过代码来执行以上存储过程来获取表Renter中的数据呢?
我们又如何将获取到的数据显示在窗体上面呢?
很简单,代码如下:
      //窗体加载时
        private void FrmMain_Load(object sender, EventArgs e)
        {
            //SqlHelper.GetConnectionSQLDb(MyXml.GetConnString())的作用是获取一个SqlConnection对象
            SqlCommand cmd= new SqlCommand("sp_test",SqlHelper.GetConnectionSQLDb(MyXml.GetConnString()));
            cmd.CommandType = CommandType.StoredProcedure;//SQL命令类型为存储过程
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);//数据适配器
            //将获取到的数据显示在DataGridView上面
            DataSet ds = new DataSet();//数据集
            adapter.Fill(ds,"Renter"); //获取记录集
            dgvRenter.DataSource = ds.Tables[0].DefaultView;
        }----------------------------------------------------------------------------------------------------------------------------------------------------------------------
//效果截图如下:
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
对于以上代码,你可能看不懂这一行代码:
//SqlHelper.GetConnectionSQLDb(MyXml.GetConnString())的作用是获取一个SqlConnection对象
SqlCommand cmd= new SqlCommand("sp_test",SqlHelper.GetConnectionSQLDb(MyXml.GetConnString()));
注:
1.sp_test是存储过程名称
2.SqlHelper.GetConnectionSQLDb(MyXml.GetConnString())的作用是获取一个SqlConnection对象
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
方法GetConnectionSQLDb()的实现代码如下:
// <summary>
        /// 获取一个SQL数据库连接对象
        /// </summary>
        /// <param name="connStr">数据连接字符串</param>
        /// <returns>返回一个数据库连接对象</returns>
        public static SqlConnection GetConnectionSQLDb(string connStr)
        {
                try
                {
                    if(sqlConn==null)
                        sqlConn=new SqlConnection();
                    sqlConn.ConnectionString = connStr;
                    sqlConn.Open();
                    return sqlConn;
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.ToString() + ex.Message);
                    return null;
                }
        }----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
您的十分满意是我追求的宗旨。
您的一点建议是我后续的动力。
