[英]How to get result from store procedure in C#
我是C#的新手。 我創建了一個有6條記錄的小table
。 我想使用store procedure
獲取這些記錄。 另外,我有兩種簡單的形式。 一種是Main Form
,用戶可以通過click on the find button
鍵入Student Id
以獲取結果。
GetStudentById
CREATE Procedure GetStudentById (@Id VARCHAR)
AS
BEGIN
SELECT * FROM dbo.Students WHERE Id = @Id
END
我試圖找到自己的解決方案。 因為,我正在學習這個。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinApp
{
public partial class WinForm : Form
{
public WinForm()
{
InitializeComponent();
}
private void CloseBtn_Click(object sender, EventArgs e)
{
this.Close();
}// End CloseBtn_Click
private string getConnectionString()
{
string conStr = ConfigurationManager.ConnectionStrings["WinApp.Properties.Settings.WinPro_dbConnectionString"].ToString();
return conStr;
}
private void FindBtn_Click(object sender, EventArgs e)
{
string SearchId = SearchInput.Text;
SqlCommand cmd = null;
using (SqlConnection con = new SqlConnection( getConnectionString() ))
{
try
{
con.Open();
cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetStudentById";
cmd.Parameters.AddWithValue("@Id", SearchId);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
cmd = null;
}
}
}// End FndBtn_Click
}
}
以上代碼來自我的主要形式。 如何將結果保存到array
並分配給second viewform controls to edit the result
?
SqlCommand cmd = null;
using (SqlConnection con = new SqlConnection( getConnectionString() ))
{
try
{
con.Open();
cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetStudentById";
cmd.Parameters.AddWithValue("@Id", SearchId);
SQLDataReader reader = cmd.ExecuteReader();
// To make your code a bit more robust you should get
// the indexes of the named columns...this is so that if
// you modified the Schema of your database (e.g. you
// added a new column in the middle, then it is more
// resilient than using fixed value index numbers).
int iId = oReader.GetOrdinal("Id");
int iFirstname = oReader.GetOrdinal("Firstname");
int iLastname = oReader.GetOrdinal("Lastname");
while(reader.Read())
{
int id = reader.GetInt32(iId);
string firstname = reader.GetString(iFirstname);
string lastname = reader.GetString(iLastname);
....
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
cmd = null;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.