如何在C#中从数据库中获取数据 [英] How to fetch data from database in C#

查看:478
本文介绍了如何在C#中从数据库中获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在sql中创建了一个数据库,其中我为每个条目提供了一个唯一的id,我想使用该唯一ID在C#中获取整个数据。帮助我尽快



编辑 - 评论中的OP代码

I have created a database in sql in which I have provided a unique id to every entry and I want to fetch the entire data in C# using that unique id. Help me asap.

Edit - OP code from comment

private void button1_Click_1(object sender, EventArgs e)
{
	SqlConnection con = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=sales;Data Source=MERITECH-PC");
	con.Open();

	SqlCommand cmd = new SqlCommand("Select * from new", con);
	cmd.Parameters.Add("@id", SqlDbType.Int).Value = 1;
	  
	SqlDataReader dr = cmd.ExecuteReader();
	if (dr.HasRows)
	{
		dr.Read();
		txt1.Text= dr[0].ToString();
		txt2.Text = dr[1].ToString();
		txt3.Text = dr[2].ToString();
		txt4.Text = dr[3].ToString();
		txt5.Text = dr[4].ToString();
	}
	con.Close();
}

推荐答案

这是您的代码(假设您的主键名为 id ):

Here is your code (assuming your primary key is named id):
private void button1_Click_1(object sender, EventArgs e)
{
	SqlConnection con = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=sales;Data Source=MERITECH-PC");
	con.Open();
 
	//notice the addition below
    SqlCommand cmd = new SqlCommand("Select * from new where id=@id", con);
	cmd.Parameters.Add("@id", SqlDbType.Int).Value = 1;
	  
	SqlDataReader dr = cmd.ExecuteReader();
	if (dr.HasRows)
	{
		dr.Read();
		txt1.Text= dr[0].ToString();
		txt2.Text = dr[1].ToString();
		txt3.Text = dr[2].ToString();
		txt4.Text = dr[3].ToString();
		txt5.Text = dr[4].ToString();
	}
	con.Close();
}


这篇关于如何在C#中从数据库中获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆