以下文章纯属是学习笔记:
数据库-mytest
数据库表 -test_table
表里字段 -
id nchar(10)
name char(20)
password char(20)
---------------------------------------------
储存过程
create procedure testProc ( @unname char(20), @unpassword char(20), @unid int output ) as insert into test_table(name,password)values(@unname,@unpassword) select @unid=count(*) from test_table
go
----------------------------------------------
下面建立一个webform
拖放三个lable 一个button 二个textbox
然后在进入codebehind中写代码 记得加上命名空间using System.Data.SqlClient;
protected
void
Page_Load(
object
sender, EventArgs e)
...
{ Label1.Text = " 用户名 " ; Label2.Text = " 密码 " ; Label3.Text = "" ; }
protected
void
Button1_Click(
object
sender, EventArgs e)
...
{ // 一个连接 一个命令 并使命令属性为存储过程类型 SqlConnection conn = new SqlConnection( @" data source=.sqlexpress;initial catalog=mytest;user id=sa;password=test " ); SqlCommand com = new SqlCommand( " testProc " , conn); com.CommandType = CommandType.StoredProcedure; // 输入参数并赋值 com.Parameters.Add( " @unname " , SqlDbType.Char, 20 ).Value = TextBox1.Text; com.Parameters.Add( " @unpassword " , SqlDbType.Char, 20 ).Value = TextBox2.Text; // 返回参数 SqlParameter idParameter = com.Parameters.Add( " @unid " , SqlDbType.Int, 20 ); idParameter.Direction = ParameterDirection.Output; // 执行 conn.Open(); com.ExecuteNonQuery(); Label3.Text = " 表有记录: " + idParameter.Value.ToString() + " 条 " ; conn.Close(); }
-----------------------------------------------
错误发现1
Size 属性具有无效大小值 0
错误原因
SqlParameter idParameter = new SqlParameter("@unid", SqlDbType.Int);
这行代码后面SqlDbType.Int 错误前是SqlDbType.Char原来是数据类弄错了
错误发现2
lable3没有输出参数,
后来发现存储过程写错了