您的位置:首页 > 其它

第三十讲 : 综合应用&存储过程 返回值参数实例

2014-04-16 00:02 363 查看
建个表先:

CREATE TABLE [dbo].[Blogs](
[blog_id] [int] IDENTITY(1,1) NOT NULL,--博客ID
[blog_name] [varchar](50) NOT NULL, --博客标题
[blog_content] [text] NOT NULL --博客内容
)
插些数据进去后,创建一个存储过程:

create proc ReturnValue
(
@id int, --查寻条件
@name varchar(100) output --要返回去的
)
as
select @name =(select blog_name from Blogs where blog_id=@id)
go
测试原码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace ReturnValue
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//连接字符串
string strConn = "server=.; database=hrms; uid=sa; pwd=123123";
string str = "select blog_id,blog_name,blog_content from [Blogs]";
private void Form1_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(strConn))
{
SqlCommand cmd = new SqlCommand(str, conn);
cmd.CommandType = CommandType.Text;
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (sdr.Read())
{
ListViewItem lvi = new ListViewItem(sdr["blog_id"].ToString());
lvi.SubItems.Add(sdr["blog_name"].ToString());
lvi.SubItems.Add(sdr["blog_content"].ToString());

listView1.Items.Add(lvi);
}
sdr.Close();
}
}
/// <summary>
/// 测试返回值
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
int id=0;
try
{
id = Convert.ToInt32(tbValue.Text.Trim());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

using (SqlConnection conn = new SqlConnection(strConn))
{
SqlCommand cmd = new SqlCommand("ReturnValue", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
cmd.Parameters.AddWithValue("@id",id);
// 下面的是定义一个返回值变量
SqlParameter name = new SqlParameter("@name",SqlDbType.VarChar,50);
name.Direction = ParameterDirection.Output;
cmd.Parameters.Add(name);

cmd.ExecuteNonQuery();

lblReturn.Text = cmd.Parameters["@name"].Value.ToString();

}
}

/// <summary>
/// 用户单击时,将自动ID填写到查寻条件框里
/// 多些一举不?呵呵,因为我实在不想手动输入
/// 你可以手输的
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
foreach(ListViewItem lvi in listView1.SelectedItems)
{
tbValue.Text = lvi.Text;
}
}
}
}
}
结果如图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: