[英]How to read and compare data from an SQL Server Express database
我試圖在C#中創建一條select語句,以檢查插入到文本框(userName)中的值是否在現有的SQL數據庫中。 我有一個名為Employee
的數據庫,其中包含一個名為EVUSERS
的表,並且它具有一個名為UName
的列。
在我的代碼中,我有一個方法從名為UserBox的文本框中獲取值。 我想知道是否有一個用於存儲選擇的臨時表,我可以將其與文本框值進行比較。
這是代碼:
private void CheckLoginExist()
{
String userName = UserBox.Text;
string connectionString = @"Data Source=.\SQLEXPRESS;Database=Employee;Integrated Security=true";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "SELECT UName FROM EVUSERS WHERE UName = @UName";
command.Parameters.AddWithValue("@UName", userName);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}
}
我目前有一個選擇,但是我不確定如何顯示它,並且可以連接到數據庫。
您需要ExecuteScalar ,而不是ExecuteNonQuery
...
connection.Open();
var name = command.ExecuteScaclar().ToString();
connection.Close();
if (name != null) {
MessageBox.Show("This name already exists");
return;
}
private void CheckLoginExist()
{
DataTable dt = new DataTable();
String userName = UserBox.Text;
string connectionString = @"Data Source=.\SQLEXPRESS;Database=Employee;Integrated Security=true";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataAdapter da = new SqlDataAdapter("SELECT UName FROM EVUSERS WHERE UName = '" + userName + "'", _conn);
da.Fill(dt);
}
}
現在,您可以使用此DataTable做任何您想做的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.