C#使用存储过程访问数据库
假设在数据库里面有一个名为 news 的数据表,添加一条记录的存储过程如下:
访问数据库的代码如下:
CREATE PROCEDURE AddNews
@id int,
@title nvarchar(200),
@content nvarchar(4000),
@publishtime datetime,
@replies int
AS
insert news (id,title,content,publishtime,replies)
values
(@id,@title,@content,@publishtime,@replies)
@id int,
@title nvarchar(200),
@content nvarchar(4000),
@publishtime datetime,
@replies int
AS
insert news (id,title,content,publishtime,replies)
values
(@id,@title,@content,@publishtime,@replies)
访问数据库的代码如下:
string source =
"server=169.254.0.1;" +
"user id=softgroup;" +
"password=1234;" +
"database=newsdb";
string source=
"server=169.254.0.1;" +
"integrated security=SSPI;" +
"database=sstinews";
SqlConnection conn = new SqlConnection(source);
conn.Open();
SqlCommand cmd=new SqlCommand("AddNews",conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@id", SqlDbType.Int, 4));
cmd.Parameters.Add(new SqlParameter("@title", SqlDbType.NVarChar, 200));
cmd.Parameters.Add(new SqlParameter("@content", SqlDbType.NVarChar,4000));
cmd.Parameters.Add(new SqlParameter("@publishtime", SqlDbType.DateTime, 8));
cmd.Parameters.Add(new SqlParameter("@replies", SqlDbType.Int, 4));
cmd.UpdatedRowSource=UpdateRowSource.None;
cmd.Parameters["@id"].Value=art.ID;
cmd.Parameters["@title"].Value=art.Title;
cmd.Parameters["@content"].Value=art.Content;
cmd.Parameters["@publishtime"].Value=art.PublishTime;
cmd.Parameters["@replies"].Value=art.Replies;
cmd.ExecuteNonQuery();
conn.Close();
"server=169.254.0.1;" +
"user id=softgroup;" +
"password=1234;" +
"database=newsdb";
string source=
"server=169.254.0.1;" +
"integrated security=SSPI;" +
"database=sstinews";
SqlConnection conn = new SqlConnection(source);
conn.Open();
SqlCommand cmd=new SqlCommand("AddNews",conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@id", SqlDbType.Int, 4));
cmd.Parameters.Add(new SqlParameter("@title", SqlDbType.NVarChar, 200));
cmd.Parameters.Add(new SqlParameter("@content", SqlDbType.NVarChar,4000));
cmd.Parameters.Add(new SqlParameter("@publishtime", SqlDbType.DateTime, 8));
cmd.Parameters.Add(new SqlParameter("@replies", SqlDbType.Int, 4));
cmd.UpdatedRowSource=UpdateRowSource.None;
cmd.Parameters["@id"].Value=art.ID;
cmd.Parameters["@title"].Value=art.Title;
cmd.Parameters["@content"].Value=art.Content;
cmd.Parameters["@publishtime"].Value=art.PublishTime;
cmd.Parameters["@replies"].Value=art.Replies;
cmd.ExecuteNonQuery();
conn.Close();
-----------------------------------------------------------------