C#连接数据库sqlserver2005,执行存储过程的实例

来源:互联网 发布:vue.js 2.0浏览器支持 编辑:程序博客网 时间:2024/06/09 20:59

C#连接数据库sqlserver2005,执行存储过程的实例:

[csharp] view plaincopy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. using System.Data;//头文件  
  7. using System.Data.SqlClient;  
  8.   
  9. namespace DBdemo3  
  10. {  
  11.     class Program  
  12.     {  
  13.         static void Main(string[] args)  
  14.         {  
  15.             //建立连接对象  
  16.             SqlConnection cnn = new SqlConnection();  
  17.             cnn.ConnectionString = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=mapdemo;Data Source=PC-20130306BGML";  
  18.             //打开连接  
  19.             cnn.Open();  
  20.   
  21.             //建立SqlParameter对象,代表存储过程的参数  
  22.             SqlParameter prm;  
  23.   
  24.             //建立执行对象  
  25.             SqlCommand cmd = new SqlCommand();  
  26.             cmd.Connection = cnn;  
  27.   
  28.             //将类型指定为存储过程,并指定存储过程名称  
  29.             cmd.CommandType = CommandType.StoredProcedure;  
  30.             cmd.CommandText = "InsStuProc";  
  31.   
  32.             //添加参数  
  33.             prm = new SqlParameter();  
  34.             prm.ParameterName = "@Sno";//参数名称  
  35.             prm.SqlDbType = SqlDbType.Char;//参数类型  
  36.             prm.Size = 6;//参数的大小  
  37.             prm.Value = "060010";//参数的值  
  38.             prm.Direction = ParameterDirection.Input;//参数的方向,输入还是输出  
  39.             cmd.Parameters.Add(prm);  
  40.   
  41.             prm = new SqlParameter();  
  42.             prm.ParameterName = "@SName";  
  43.             prm.SqlDbType = SqlDbType.VarChar;  
  44.             prm.Size = 10;  
  45.             prm.Value = "张三";  
  46.             prm.Direction = ParameterDirection.Input;  
  47.             cmd.Parameters.Add(prm);  
  48.   
  49.             prm = new SqlParameter();  
  50.             prm.ParameterName = "@Age";  
  51.             prm.SqlDbType = SqlDbType.TinyInt;  
  52.             prm.Value = 20;  
  53.             prm.Direction = ParameterDirection.Input;  
  54.             cmd.Parameters.Add(prm);  
  55.   
  56.             //执行存储过程  
  57.             cmd.ExecuteNonQuery();  
  58.               
  59.   
  60.         }  
  61.     }  
  62. }  
0 0