简体   繁体   English

从SQL Server检索用户数据

[英]Retrieving user data from SQL Server

I'm trying to figure out how to get my user data from the user I login with. 我正在试图弄清楚如何从我登录的用户那里获取用户数据。 I know how to get all the data to a gridview but not how to get the specific data for the user that are logged into my program. 我知道如何将所有数据都提供给gridview,但不知道如何获取登录到我的程序的用户的特定数据。

This is how I login if that can be to any use 这是我登录的方式,如果可以用于任何用途

SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=(local);Initial Catalog=MyDb;Integrated Security=True";

con.Open();

string txtUs = TxtUser.Text; 
string txtPas = TxtPass.Text;

string query = "SELECT * FROM User WHERE Username=@user and Password =@pass";

SqlCommand cmd = new SqlCommand(query,con);
cmd.Parameters.Add(new SqlParameter("@user",txtUs));
cmd.Parameters.Add(new SqlParameter("@pass",txtPas));

SqlDataReader dr = cmd.ExecuteReader();

int count = 0;

while (dr.Read())
{
    count = +1;
}

if (count == 1)
{
    this.Hide();
    var main = new Main();
    main.Closed += (s, args) => this.Close();
    main.Show();
}

First, your count = +1 should be count++ . 首先,你的count = +1应该是count++ Now the count is reset on every iteration. 现在,每次迭代都会重置计数。 Also, if you have an index on the user name, there is no need to check the number of rows. 此外,如果您有用户名的索引,则无需检查行数。

Then you need to set an object or a set of variables to the values from the database, like this: 然后,您需要将一个对象或一组变量设置为数据库中的值,如下所示:

string username = null;
if (dr.Read())
{
    username = (string)dr["username"];
}

Then act accordingly. 然后采取相应行动 You could store these variables in a static member to keep it alive during execution of your application. 您可以将这些变量存储在静态成员中,以使其在应用程序执行期间保持活动状态。

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

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