using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
namespace ProcedureTest
{
public partial class Add : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataBind();
}
}
/// <summary>
/// 存储过程模式
/// 存储过程优势:
/// 1.执行性能好
/// 2.数据安全性高,有效防止sql注入攻击
/// 3.易于维护
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button1_Click(object sender, EventArgs e)
{
string strConn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;//数据库连接字符串
SqlConnection conn = new SqlConnection(strConn);//建立数据库连接
conn.Open();//打开数据库连接
SqlCommand cmd = new SqlCommand();//非查询类语句
cmd.CommandText = "ADDStudent";//要执行的存储过程
cmd.Connection = conn;//关联数据库连接
cmd.CommandType = System.Data.CommandType.StoredProcedure;//存储过程模式解释命令字符串
cmd.ExecuteNonQuery();//执行存储过程
conn.Close();//关闭数据库连接
GridView1.DataBind();
}
/// <summary>
/// sql语句模式
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button2_Click(object sender, EventArgs e)
{
////数据库连接字符串
//string conStr = "Data Source=.;Initial Catalog=Student;Integrated Security=True";
////建立数据连接
//SqlConnection conn = new SqlConnection(conStr);
string strConn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;//数据库连接字符串
using (SqlConnection conn = new SqlConnection(strConn))//建立数据库连接
{
conn.Open();//打开数据库连接
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO UserInfo VALUES('SQL语句','123','true')";//要执行的SQL语句
cmd.Connection = conn;//关联数据库连接
cmd.CommandType = System.Data.CommandType.Text;//SQL文本模式解释命令字符串
cmd.ExecuteNonQuery();//执行SQL语句
GridView1.DataBind();
}
}
存储过程
CREATE procedure ADDStudent
AS
BEGIN
INSERT INTO UserInfo VALUES('存储过程','123','true')
END
GO