简体   繁体   English

C#SQL结果作为变量

[英]C# SQL result as variable

On my main form I have queried the user id on submission. 在主表单上,我已查询提交的用户ID。 Once I save the id to a variable how can I call it on another windows form in the same application? 将ID保存到变量后,如何在同一应用程序的另一个Windows窗体上调用它?

This is what I have so far 这就是我到目前为止

    private void btnLogin_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("Data Source=.database.windows.net;Initial Catalog=userlogins;Persist Security Info=True;User ID=****;Password=****");
        SqlDataAdapter sda = new SqlDataAdapter("Select ID from users where username='" + txtUsername.Text + "' and password='" + txtPassword.Text + "' ", con);
        SqlCommand cmd = con.CreateCommand();
        con.Open();

        // save SQL ID to variable
        cmd.CommandText = "Select Id from users where username = '" + txtUsername.Text + "'";
        int sqlid = ((int)cmd.ExecuteScalar());

Any information would be appreciated, I really need the ID on multiple other pages! 任何信息将不胜感激,我真的需要其他多个页面上的ID!

If you are using the ExecuteScalar() method, it's important to remember that this will only return the contents of the first cell in your results, so it can generally help to use in conjunction with a TOP 1 statement. 如果使用的是ExecuteScalar()方法,请务必记住,这只会返回结果中第一个单元格的内容,因此通常可以与TOP 1语句结合使用。

Additionally, you should consider refactoring your code to use parameterization, which should help avoid nastiness like SQL Injection and will also help mitigate any syntax issues : 此外,您应该考虑重构代码以使用参数化,这应该有助于避免像SQL Injection这样的麻烦,并且还可以减轻任何语法问题:

// Build your connection
using(var con = new SqlConnection("your-connection-string"))
{
     // Build your query
     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 your connection
          con.Open();
          // Add your parameters
          cmd.Parameters.AddWithValue("@username", txtUsername.Text);
          cmd.Parameters.AddWithValue("@password", txtPassword.Text);

          // Get your ID
          var sqlid = Convert.ToInt32(cmd.ExecuteScalar());
          // Do something here
     }
}

One way to do this is with events: 一种方法是使用事件:

public class IdChangedEventArgs : EventArgs
{
  int ChangedId {get;set;};
}

public delegate void IdChangedEventHandler(object sender, IdChangedEventArgs e);
public event IdChangedEventHandler IdChangedEvent;
private void btnLogin_Click(object sender, EventArgs e)
{
  int sqlid = ((int)cmd.ExecuteScalar());
  IdChangedEvent(this, new IdChangedEventArgs {ChangedId = sqlid;} );
}

In each of your interested forms, subscribe to the events. 在您感兴趣的每种表单中,订阅事件。 When handled, update your GUI however you want. 处理后,根据需要更新您的GUI。

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

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