C# asp.net SQL存储过程写法Insert 插入语句,及其在asp.net中的调用方法
时间:2010-09-02 来源:chinaallyes
C# asp.net SQL存储过程写法Insert 插入语句,及其在asp.net中的调用方法
1、SQL存储过程语句:
向SQL里插入一条记录:
CREATE PROCEDURE dbo.Ta_test
@names nchar(255),
@sex nchar(255)
AS
insert into T_a (names,sex)
values (@names,@sex)
GO
2、SQL连接类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
/// <summary>
///DB 的摘要说明
/// </summary>
public class DB
{
public DB()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
public static SqlConnection CreateDBcon()
{
return new SqlConnection("data source=(local);user ID = sa;password=*0.-+;initial catalog=SongYe_WLJC");
}
}
3、webform页面语句(类的调用,存储过程的调用 方法):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Net;
using System.Text;
public partial class Administrator_T_a : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conns = DB.CreateDBcon(); //调用SQL类
SqlCommand Cmd = new SqlCommand("Ta_test", conns);
Cmd.Parameters.Add(new SqlParameter("@names", SqlDbType.NChar,255)); //存储过程参数
Cmd.Parameters.Add(new SqlParameter("@sex", SqlDbType.NChar,255));
Cmd.Parameters["@names"].Value = TextBox1.Text.Trim();
Cmd.Parameters["@sex"].Value = TextBox2.Text.Trim();
Cmd.CommandText = "Ta_test"; //调用存储过程
Cmd.CommandType = CommandType.StoredProcedure;
conns.Open();
Cmd.ExecuteNonQuery(); //执行存储过程
conns.Close();
TextBox1.Text = "";
TextBox2.Text = "";
string infos = "测试成功!";
Response.Write("<script>alert('" + infos + "')</script>");
}
}
本人学习时测试用的,是成功的,有兴趣的同志们可以学习一下。