ASP.NET从入门到精通笔记第9章-使用Command对象调用存储过程

9.3.5使用Command对象调用存储过程

前提是创建一个数据库Music,表名为catalog,两列分别为id int , name varchar(50)

首先,在SqlServer中创建存储过程

打开SqlServer->新建查询->输入如下语句(注,原书中有一处错误,第一句末尾的go是需要换行的)

if object_id('InsertMusic') is not null drop proc InsertMusic
go

Create proc InsertMusic
(@id int,@name varchar(50))
as
insert into catalog values(@id,@name)
go

说明:

第一句是检查是不是已经存在同名存储过程

后面的语句中@id和@name是要输入的参数

定义存储过程的个试试

Create proc 存储过程名
(@参数1 参数类型,@参数2 参数类型)
as
SQL语句,其中值用参数1和参数2代替


然后新建一个网站,添加default页面,在页面中添加一个GridView,绑定到你的数据

添加两个TextBox,ID分别为TextBox1和TextBox2

default.aspx.cs文件中添加命名空间

using System.Data.SqlClient;
using System.Configuration;
using System.Data;

添加一个Button,在Click事件中添加如下代码

        SqlConnection MyCon = GetConnection();
        MyCon.Open();
        SqlCommand MyCmd = new SqlCommand("InsertMusic", MyCon);
        MyCmd.CommandType = CommandType.StoredProcedure;
        MyCmd.Parameters.Add("@id", SqlDbType.Int).Value = this.TextBox1.Text.Trim();
        MyCmd.Parameters.Add("@name", SqlDbType.VarChar, 50).Value = this.TextBox2.Text.Trim();
        MyCmd.ExecuteNonQuery();
        MyCon.Close();
        this.DataBind();

web.config中,定义连接字串




定义GetConnection方法

public SqlConnection GetConnection()
    {
        string MyStr = ConfigurationManager.AppSettings["ConnectString"].ToString();
        SqlConnection MyCon = new SqlConnection(MyStr);
        return MyCon;
    }


至此,运行,成功

总结:

用Command对象调用存储过程关键的地方是设置Command对象的CommandType属性值为CommandType.StoredProcedure;

MyCmd.CommandType = CommandType.StoredProcedure;

 MyCmd.Parameters.Add()方法给参数赋值


你可能感兴趣的:(ASP.NET)