我正在嘗試爲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