C#连接数据库sqlserver2005,执行存储过程的实例:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Data;//头文件
- using System.Data.SqlClient;
- namespace DBdemo3
- {
- class Program
- {
- static void Main(string[] args)
- {
- //建立连接对象
- SqlConnection cnn = new SqlConnection();
- cnn.ConnectionString = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=mapdemo;Data Source=PC-20130306BGML";
- //打开连接
- cnn.Open();
- //建立SqlParameter对象,代表存储过程的参数
- SqlParameter prm;
- //建立执行对象
- SqlCommand cmd = new SqlCommand();
- cmd.Connection = cnn;
- //将类型指定为存储过程,并指定存储过程名称
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.CommandText = "InsStuProc";
- //添加参数
- prm = new SqlParameter();
- prm.ParameterName = "@Sno";//参数名称
- prm.SqlDbType = SqlDbType.Char;//参数类型
- prm.Size = 6;//参数的大小
- prm.Value = "060010";//参数的值
- prm.Direction = ParameterDirection.Input;//参数的方向,输入还是输出
- cmd.Parameters.Add(prm);
- prm = new SqlParameter();
- prm.ParameterName = "@SName";
- prm.SqlDbType = SqlDbType.VarChar;
- prm.Size = 10;
- prm.Value = "张三";
- prm.Direction = ParameterDirection.Input;
- cmd.Parameters.Add(prm);
- prm = new SqlParameter();
- prm.ParameterName = "@Age";
- prm.SqlDbType = SqlDbType.TinyInt;
- prm.Value = 20;
- prm.Direction = ParameterDirection.Input;
- cmd.Parameters.Add(prm);
- //执行存储过程
- cmd.ExecuteNonQuery();
- }
- }
- }