IT SHARE EDU
Hướng dẫn cách truy vấn dữ liệu đơn đơn dòng dùng cách thông thường có dùng SqlDataReader và ExecuteReade
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace kncsdlhocba
{
public partial class Truyvandulieudondong : Form
{
public Truyvandulieudondong()
{
InitializeComponent();
}
SqlConnection conec = null;
string ketnoi = @”Server =DESKTOP-CR8PM8T\SQLEXPRESS; Database=CSDLSANPHAM ; User ID=sa; pwd =123″;
private void btnXem_Click(object sender, EventArgs e)
{
if (conec==null)
{
conec = new SqlConnection(ketnoi);
}
if (conec.State == ConnectionState.Closed)
{
conec.Open();
}
SqlCommand command = new SqlCommand();
command.CommandType = CommandType.Text;
command.CommandText = “select * from SanPham where ma=” + txtMamuontim.Text;
command.Connection = conec;
SqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
txtMa.Text = reader.GetInt32(0) + “”;
txtTen.Text = reader.GetString(1);
txtGia.Text = reader.GetInt32(2).ToString();
}
reader.Close();
}
Cách kết dữ liệu sql server với c# truy vân dữ liệu có dùng SqlParameter
private void txtpara_Click(object sender, EventArgs e)
{
if (conec==null)
{
conec = new SqlConnection(ketnoi);
}
if (conec.State== ConnectionState.Closed)
{
conec.Open();
}
SqlCommand command = new SqlCommand();
command.CommandType = CommandType.Text;
command.CommandText = ” select * from SanPham where ma=@ma”;
command.Connection = conec;
SqlParameter parama = new SqlParameter(“@ma”, SqlDbType.Int);
parama.Value = txtMamuontim.Text;
command.Parameters.Add(parama);
SqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
txtMa.Text = reader.GetInt32(0) + “”;
txtTen.Text = reader.GetString(1);
txtGia.Text = reader.GetInt32(2) + “”;
}
reader.Close();
}
Video Hướng dẫn học lập trình c# cách truy vấn dữ liệu đơn dòng