如何从 sql 字段获取值到 c# 中的标签?

How to get value from an sql field to a label in c#?

我对 c# 还是很陌生,所以这可能很愚蠢,但我希望能够显示 table 中的字段字段中的单个值 (tuition_fee) =20=] 在 c# 中的标签取决于已输入的 "tuition_code".. (studenttuition_code) 是与 SQL)

中比较的学费代码

Here is my code so far:

using (SqlConnection con = new SqlConnection(_connectionstring))
{
   con.Open();
   string sqlQuery = string.Format("SELECT tuition_fee FROM Tuition WHERE tuition_code = '{0}'", studenttuition_code);
   SqlCommand cmd = new SqlCommand(sqlQuery, con);
   SqlDataReader dr = cmd.ExecuteReader();
   while (dr.Read())
   {
     lblAmount.Text = dr.GetValue; 
   }
   con.Close(); 
}

This is what I have in SQL for the Tuition Table:

CREATE TABLE Tuition
(
    tuition_code VARCHAR (6) NOT NULL,
    tuition_instrument VARCHAR (3) NOT NULL,
    tuition_lessonno INT NOT NULL,
    tuition_roomcode VARCHAR (3) NOT NULL,
    tutor_id VARCHAR (4) NOT NULL,
    tuition_fee DECIMAL NOT NULL,
    CONSTRAINT pk_tuition PRIMARY KEY (tuition_code),
    CONSTRAINT fk_tuitionroomcode FOREIGN KEY (tuition_roomcode) REFERENCES Room(room_code),
    CONSTRAINT fk_tutorfortuiton FOREIGN KEY (tutor_id) REFERENCES Tutor(tutor_id)
)

不知道我是否理解你的问题,希望能帮到你。

试试这个风箱。

using (SqlConnection con = new SqlConnection(_connectionstring))
{
  con.Open();
  string sqlQuery = "SELECT TOP 1 tuition_fee FROM Tuition WHERE     
  tuition_code = @tuitionCode";
  SqlCommand cmd = new SqlCommand(sqlQuery, con);
  cmd.Parameters.AddWithValue("@tuitionCode", studenttuition_code);
  SqlDataReader dr = cmd.ExecuteReader();
  while (dr.Read())
  {
    lblAmount.Text = dr["tuition_fee"].ToString();
  }
  con.Close(); 
}
using (var con = new SqlConnection(_connectionstring))
{
   con.Open();
   string sqlQuery = "SELECT tuition_fee FROM Tuition WHERE tuition_code = @tuitionCode";
   var cmd = new SqlCommand(sqlQuery, con);
   cmd.Parameters.AddWithValue("@tuitionCode", studenttuition_code);
   var dr = cmd.ExecuteReader();
   while (dr.Read())
   {
     lblAmount.Text = dr.GetValue; 
   }
   con.Close(); 
}

您应该在查询中使用参数化。这通过避免 SQL 注入使您的查询安全,并且还使格式化更容易,因为您不必担心使用单引号和所有爵士乐。

你只需要做一次 dr.Read() 除非你的 SQL 得到不止一行(它可能不应该)。 您还应该在每个 SQL 对象上使用 using,因为它们都实现了 IDisposable。

string sqlQuery = "SELECT tuition_fee FROM Tuition WHERE tuition_code = @tuitionCode";
using (var con = new SqlConnection(_connectionstring))
{
    con.Open();
    using (var cmd = new SqlCommand(sqlQuery, con))
    {
        cmd.Parameters.AddWithValue("@tuitionCode", studenttuition_code);
        using (var dr = cmd.ExecuteReader())
        {
            dr.Read();
            lblAmount.Text = dr.GetString(0);
        }
    }
    con.Close();
}