我如何读出带有名称的ID

时间:2019-01-23 16:57:21

标签: c# sql-server visual-studio

我想编写一些程序,应该从数据库中读取ID。您只会得到在文本框中键入的名称,并且应该从该名称中搜索ID并将其发布。

我试图更改字符串和sql语句

private void button2_Click(object sender, EventArgs e)
        {
            SqlConnection con1 = new SqlConnection(conString);
            con1.Open();
            if (con1.State == System.Data.ConnectionState.Open)
            {
                string nameInput = txtNameInput.Text;
                string query = "SELECT id " + "FROM test" + "WHERE name LIKE 
                '" + nameInput + "'";
                txtIdOutput.Text = query;
                SqlCommand cmd = new SqlCommand(query, con1);
            }
        }

当我输入名称并按下按钮时,我将在第二个文本框中看到sql语句,但没有看到id。我想要ID

1 个答案:

答案 0 :(得分:2)

这不是完美的实现,但它应该可以帮助您入门:

txtIdOutput.Text = string.Empty;

using(var connection = new SqlConnection(conString))
{
    connection.Open();

    using(var command = connection.CreateCommand())
    {
         command.CommandText = "SELECT id FROM test WHERE name LIKE @name";
         command.Parameters.AddWithValue("@name", txtNameInput.Text);

          using(var reader = command.ExecuteReader())
          {
               while(reader.Read())
               {
                   txtIdOutput.Text += reader.GetValue(0).ToString();
               }
          }
    }
}