我正在尝试为 Windows 窗体应用程序项目创建一个登录工具。我正在使用 Visual Studio 2010 和 MS Sql Server 2008。
我引用了这篇文章: http: //www.codeproject.com/Articles/4416/Beginners-guide-to-accessing-SQL-Server-through-C
这是我的名为 user 的数据库表:
我TextBox1
有用户名、TextBox2
用户密码和Button1
启动登录过程。这是我的Button1_Click
方法代码:
private void button1_Click(object sender, EventArgs e)
{
string kullaniciAdi; // user name
string sifre; // password
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = "Data Source=localhost; database=EKS; uid=sa; pwd=123; connection lifetime=20; connection timeout=25; packet size=1024;";
myConn.Open();
try
{
SqlDataReader myReader;
string myQuery = ("select u_password from user where u_name='" + textBox1.Text + "';");
SqlCommand myCommand = new SqlCommand(myQuery,myConn);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
sifre = myReader["u_password"].ToString();
}
}
catch (Exception x)
{
MessageBox.Show(x.ToString());
}
myConn.Close();
}
我对 C# 没有太多经验,但我认为我错过了一些小事来做对。下面我分享我捕获的异常消息。你能告诉我我错过了什么吗?(第 33 行是myReader = myCommand.ExecuteReader();
)
考虑到给出的答案,我更新了我的尝试块,如下所示,但它仍然不起作用。
try
{
SqlDataReader myReader;
string myQuery = ("select u_password from [user] where u_name=@user");
SqlCommand myCommand = new SqlCommand(myQuery, myConn);
myCommand.Parameters.AddWithValue("@user", textBox1.Text);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
sifre = myReader["u_password"].ToString();
}
if (textBox2.Text.Equals(sifre))
{
Form2 admnPnl = new Form2();
admnPnl.Show();
}
}
根据 sine 的建议如下更改整个代码后,屏幕截图如下: 而且我认为,不知何故,我无法将数据库中的密码分配给字符串 sifre。
代码:
string sifre = "";
var builder = new SqlConnectionStringBuilder();
builder.DataSource = "localhost";
builder.InitialCatalog = "EKS";
builder.UserID = "sa";
builder.Password = "123";
using (var conn = new SqlConnection(builder.ToString()))
{
using (var cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "select u_password from [user] where u_name = @u_name";
cmd.Parameters.AddWithValue("@u_name", textBox1.Text);
conn.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var tmp = reader["u_password"];
if (tmp != DBNull.Value)
{
sifre = reader["u_password"].ToString();
}
}
if (textBox2.Text.Equals(sifre))
{
try
{
AdminPanel admnPnl = new AdminPanel();
admnPnl.Show();
}
catch (Exception y)
{
MessageBox.Show(y.ToString());
}
}
else
{
MessageBox.Show("incorrect password!");
}
}
}
}