我正在尝试为Windows窗体应用程序项目制作登录工具。我使用Visual Studio 2010和MS SQL Server 2008的从Sql Server 2008获取数据与C#
我引用这篇文章: http://www.codeproject.com/Articles/4416/Beginners-guide-to-accessing-SQL-Server-through-C
,这里是我的数据库表命名用户:
我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();
)
Considerin给出答案,我更新了我的try块在下面,但它仍然无法正常工作。
try
{
SqlDataReader myReader;
string myQuery = ("select u_password from [user] where [email protected]");
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();
}
}
按正弦的建议改变如下整个代码后,截图也低于: ,我想,不知何故,我不能在数据库字符串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!");
}
}
}
}
嗨,我附加它作为图像。在我的问题结尾 –
尝试将'FROM user'更改为'FROM EKS.dbo.user' – makciook
您应该使用Parameters for Queries !!! – makim