cunchuguocheng.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="cunchuguocheng.aspx.cs" Inherits="cunchuguocheng" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
ID:<asp:TextBox ID="txt_userid" runat="server"></asp:TextBox>
<br />
姓名:<asp:TextBox ID="txt_username" runat="server"></asp:TextBox>
<br />
年龄:<asp:TextBox ID="txt_userage" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="提交" OnClick="Button1_Click" />
<br />
<asp:Label ID="Label1" runat="server" ></asp:Label>
</div>
</form>
</body>
</html>
cunchuguocheng.aspx.cs:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class cunchuguocheng : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source = (local); Initial Catalog = user; Integrated Security = True");
SqlCommand com =new SqlCommand("insertuser",con);
com.CommandType = CommandType.StoredProcedure;
//先清空参数数组,然后再逐项为存储过程中的变量赋值
com.Parameters.Clear();
com.Parameters.Add(new SqlParameter("@userid", SqlDbType.Char, 5));
com.Parameters["@userid"].Value = txt_userid.Text;
com.Parameters.Add(new SqlParameter("@username", SqlDbType.Char, 50));
com.Parameters["@username"].Value = txt_username.Text;
com.Parameters.Add(new SqlParameter("@userid", SqlDbType.Int, 20));
com.Parameters["@userage"].Value = int.Parse(txt_userage.Text);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
int records = Convert.ToInt32(com.ExecuteNonQuery());
if (records > 0)
{
Label1.Text = "添加成功";
}
else
{
Label1.Text = "添加失败";
}
com.Dispose();
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
不运行下面两条语句就正确:说明这个年龄这里是有问题的,把有关年龄的全部程序都删除,就会正确运行。
//com.Parameters.Add(new SqlParameter("@userid", SqlDbType.Int, 20));
// com.Parameters["@userage"].Value = int.Parse(txt_userage.Text);
SQL Server中的存储过程:
错误:
CREATE PROCEDURE insertuser
@userid char(5),
@username char(50),
@userage int
AS
BEGIN
insert into users(userid,username,userage) values(@userid,@username,@userage)
END
GO
删掉userage就正确:
CREATE PROCEDURE insertuser
@userid char(5),
@username char(50)
AS
BEGIN
insert into users(userid,username) values(@userid,@username)
END
GO
