将SQL结果声明为变量

时间:2016-04-05 17:47:29

标签: c# sql variables global

我需要将登录用户的ID发送到多个窗体,但无法弄清楚。如何在多个表单上调用变量?

private void btnUpdate_Click(object sender, EventArgs e)
using(var con = new SqlConnection("connectionstring"))
{
 var query = "SELECT TOP 1 ID FROM users WHERE username = @username AND password = @password";
 // Build a command to execute your query
 using(var cmd = new SqlCommand(con,query))
 {
      // Open connection
      con.Open();
      // Add your parameters
      cmd.Parameters.AddWithValue("@username", txtUsername.Text);
      cmd.Parameters.AddWithValue("@password", txtPassword.Text);

      // Get ID
      var sqlid = Convert.ToInt32(cmd.ExecuteScalar());
 }
}

我被困了几个小时而无法继续

2 个答案:

答案 0 :(得分:0)

  

如何在多个表单上调用变量?

从您的按钮点击事件中取出代码。将它放在共享库中的一个类中,该类可以由多个表单访问。

您还应该创建一个User类(和UserRepository),而不是只传递没有上下文的ID。

答案 1 :(得分:0)

这就是D Stanley所说的。

用户数据结构

public class MyUser
{
    public int ID;
    public string UserName;
    public MyUser(int id, string userName)
    {
        ID = id;
        UserName = userName;
    }
}

数据库接口类

public class UserContext
{
    private ConnectionString = ""

    // 1st constructor you pass in connection string.
    public UserContext(string connectionString)
    {
        ConnectionString = connectionString;
    }

    // 2nd constructor you use the one in the web.config file.
    public UserContext()
    {
        ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString;
    }

    public int GetUserID(string userName, string password)
    {
        // declare the result variable.
        MyUser result

        using(var con = new SqlConnection(ConnectionString))
        {

            var query = "SELECT TOP 1 ID FROM users WHERE username = @username AND password = @password";
            // Build a command to execute your query
             using(var cmd = new SqlCommand(con,query))
             {
                  // Open connection
                  con.Open();
                  // Add your parameters
                  cmd.Parameters.AddWithValue(userName);
                  cmd.Parameters.AddWithValue(password);

                  // Get ID
                  var sqlid = Convert.ToInt32(cmd.ExecuteScalar());
                  result = new MyUser(sqlid, userName);

             }
        }
        return result;
    }
}

现在您要做的就是创建一个数据库上下文对象并传入属性。

private void btnUpdate_Click(object sender, EventArgs e)
{
    // database context.
    UserContext UC  = new UserContext();

    // Get user.
    MyUser currentUser = UC.GetUserID(txtUserName.Text, txtPassword.Text);

    // now you can access userid from the User data-structure object.
    var id = currentUser.ID; 
}