我想从我的数据库中获取数据。 表名为 MsUser,包含用户 ID、用户名和密码。 有好几排。
表格说明: 我有登录,需要用户名和密码才能登录。 登录后打开交易表单,在该表单中将使用标签显示 userId,userID 基于已登录的用户名。
这是我用来匹配用户名和密码的代码 对不起,如果我的英语不好。 非常感谢您的帮助,真的。
private void btnLogin_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\ProgII Project\MoneyManager\MoneyManager\MsUser.mdf;Integrated Security=True;User Instance=True");
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) From MsUser where username='"+txtUsername.Text+"' and password='"+txtPassword.Text+"'",cn);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString()=="1")
{
this.Hide();
}
else
{
MessageBox.Show("your id or password is wrong");
}
}
最佳答案
如果您恰好返回一行、一列(例如 SELECT COUNT(*)
),请使用 SqlCommand 及其 .ExecuteScalar() 方法 - 无需承担所有开销DataTable 只为单个值!
使用这样的东西:
private void btnLogin_Click(object sender, EventArgs e)
{
// define query - and **ALWAYS** use parameters!
string query = "SELECT COUNT(*) FROM dbo.MsUser WHERE username = @UserName AND password = @password);";
// set up connection and command
using (SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\ProgII Project\MoneyManager\MoneyManager\MsUser.mdf;Integrated Security=True;User Instance=True"))
using (SqlCommand cmd = new SqlCommand(query, cn))
{
// define parameters and provide values
cmd.Parameters.Add("@username", SqlDbType.VarChar, 100).Value = txtUserName.Text;
cmd.Parameters.Add("@password", SqlDbType.VarChar, 100).Value = txtPassword.Text;
// open connection, execute command, close connection
cn.Open();
var result = cmd.ExecuteScalar();
cn.Close();
// if result is not null and can be converted to an int....
if(result != null)
{
int userCount;
if(int.TryParse(result.ToString(), out userCount))
{
// OK, you have a good value - if it's > 0, your user entry exists....
if (userCount > 0)
{
// success - user exists with password
}
else
{
// no success - no such entry
}
}
else
{
// you didn't get a numeric value......
}
}
else
{
// you didn't get any value......
}
}
}
另外:请确保您永远不会在您的数据库表中以纯文本的形式存储密码!!
更新:如果您需要检索 UserId
(而不仅仅是计数),请使用如下查询:
string query = "SELECT UserId FROM dbo.MsUser WHERE username = @UserName AND password = @password);";
然后检查您是否取回了有效的 UserId
(不确定可能是什么数据类型......)
var result = cmd.ExecuteScalar();
// checking if we got something (or null)
if (result != null)
{
string userId = result.ToString();
}
else
{
// we didn't get any "UserId" back -> invalid combination of "username" and "password"
}
关于c# - 从数据库中获取一个数据单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27794230/