简体   繁体   English

如何从C#中的数据库中获取用户名和密码?

[英]How can I get a username and password from my database in C#?

I have the following code in my btn_click event: 我在btn_click事件中有以下代码:

Sqlconnection con = new Sqlconnection("server=.;database=bss;user id=ab;pwd=ab");
con.open();
SqlCommand cmd = new Sqlcommand("select * from login where username='" 
+ txt4name.Text + "' and pwd='" + txt4pwd.Text + "'", con);

SqlDataReader reader = cmd.execute Reader();

Where login is the table and username and pwd are its fields. 其中login是表, usernamepwd是其字段。 After this code all the values are stored in the reader object. 在此代码之后,所有值都存储在reader对象中。 I want to store username and pwd in the separate variables. 我想在单独的变量中存储usernamepwd

How can I accomplish this? 我怎么能做到这一点?

In general, when accessing your DB, you should be using something similar to this instead to eliminate SQL injection vulnerabilities: 通常,在访问数据库时,您应该使用与此类似的东西来消除SQL注入漏洞:

using (SqlCommand myCommand = new SqlCommand("SELECT * FROM USERS WHERE USERNAME=@username AND PASSWORD=HASHBYTES('SHA1', @password)", myConnection))
    {                    
        myCommand.Parameters.AddWithValue("@username", user);
        myCommand.Parameters.AddWithValue("@password", pass);

        myConnection.Open();
        SqlDataReader myReader = myCommand.ExecuteReader())
        ...................
    }

But more realistically to store credentials, you should be using something like the Membership system instead of rolling your own. 但更真实地存储凭据,您应该使用诸如Membership系统之类的东西,而不是滚动自己的。

You're running a huge risk of sql injection with that. 你正在冒着sql注入的巨大风险。 Use SQL Parameters for values into SqlCommands. 将SQL参数用于SqlCommands中的值。

If you mean c# variables, and if you want to get them from db, just do this: 如果你的意思是c#变量,如果你想从db获取它们,那么就这样做:

SqlDataReader reader = cmd.execute Reader();
if (reader.Read())
{
    string username = reader["username"];
    string pwd = reader["password"];
}

While you are at it, parameterize your query and prevent sql injection: 当你在它时,参数化你的查询并防止SQL注入:

SqlCommand cmd = new Sqlcommand("select * from login where username=@username and pwd=@pwd", con);
cmd.Parameters.AddWithValue("@username", txt4name.Text);
cmd.Parameters.AddWithValue("@pwd", txt4pwd.Text);

Definitely heed the advice about SQL injection but here is the answer to your question: 绝对注意关于SQL注入的建议,但这里是你的问题的答案:

String username;
String pwd;

int columnIndex = reader.GetOrdinal("username");

if (!dataReader.IsDBNull(columnIndex))
{
    username = dataReader.GetString(columnIndex);
}

columnIndex = reader.GetOrdinal("pwd");

if (!dataReader.IsDBNull(columnIndex))
{
    pwd = dataReader.GetString(columnIndex);
}
private void but_login_Click(object sender, EventArgs e)
{
    string cn = "Data Source=.;Initial Catalog=mvrdatabase;Integrated Security=True";
    SqlConnection con = new SqlConnection(cn);
    con.Open();
    SqlCommand cmd = new SqlCommand("select count (*) from logintable where username ='" + txt_uname.Text + "'and password='" + txt_pass.Text + "'", con);
    int i = Convert.ToInt32(cmd.ExecuteScalar());
    con.Close();

    if (i == 1)
    {
        Form2 f2 = new Form2();
        MessageBox.Show("User login successfully........");
        this.Hide();
        f2.Show();
    }
    else
    {
        MessageBox.Show("INCORRECT USERID AND PASSWORD", "Error");
    }
}
string userName =  txt4name.Text;
string password =  txt4pwd.Text;

Is that really what you want? 这真的是你想要的吗? Just to get that data into variables? 只是将数据转化为变量?

You really need to use parameterized SQL. 您确实需要使用参数化SQL。 There's an example here Furthermore, your question doesn't really make sense; 这里有一个例子此外,你的问题确实没有意义; you want the username and password in seperate variables? 你想要单独的变量用户名和密码? they already are seperate in your example. 他们已经在你的例子中分开了。 If you are unable to assign them to strings I suggest following some tutorials . 如果您无法将它们分配给字符串,我建议您遵循一些教程

Another approach is to load the reader results into a DataTable like so: 另一种方法是将读取器结果加载到DataTable中,如下所示:

DataTable Result = new DataTable();

Result.Load(reader);

If your login table only contains two columns (userName and password) that are unique you end up with Result containing only one row with the information. 如果您的登录表只包含两个唯一的列(userName和password),则最终只有一行包含一行信息。 You can then get the column values from each column: 然后,您可以从每列获取列值:

string userName = Result.Rows[0].Field<string>("userName");
string password = Result.Rows[0].Field<string>("pwd");

您通常可以在MSDN上找到基本用法示例,例如SqlDataReader

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM