在WPF Desktop应用程序中从数据库检索数据

时间:2018-08-21 06:42:06

标签: c# sql sqlite

我是C#的新手,我刚刚学习了如何在WPF应用程序中将数据输入到database.mdf的数据表中。

这是通过以下代码完成的

class Com extends Component {
    constructor(props){
        super(props);
        this.createRef = this.createRef.bind(this);
    }
    createRef(elem){
        //use elem and get the html element.
    }
    render() {
        return (
            <div ref={(elem) => this.createRef(elem)} >
                <span>hey</span>
            </div>
        );
    }
}

当前通过登录页面登录后,有一个详细信息页面,我想在其中显示以前存储在我的数据库中的详细信息,例如名字,姓氏,年龄。请问可以从数据库中检索所有这些参数数据的SqlCommands是什么?

1 个答案:

答案 0 :(得分:0)

在您的位置,我将在应用程序中添加User类

public class user
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string MailAddress{ get; set; }
}


//You can keep your Logged user in a static class


public static class PublicParameters
{ 
  public static User CurrentUser;

  //Define only one connection string in your application.
  public static string ConnectionString= @"Data Source=   (LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated 
 Security=True;"
}




    void Login()
    {
        using (SqlConnection sqlConn = new SqlConnection(ConnectionString))
        {
            using (SqlCommand sqlComm = new SqlCommand("SELECT COUNT(1) FROM tbl WHERE Username=@Username AND Password=@Password", sqlConn))
            {
                if (sqlComm.Connection.State == System.Data.ConnectionState.Closed)
                    sqlComm.Connection.Open();
                SqlDataReader sqlRd = sqlComm.ExecuteReader();
                sqlComm.Parameters.AddWithValue("@Username", txtbxUsername.Text);
                sqlComm.Parameters.AddWithValue("@Password", pswbxPassword.Password);

                //Your username column must be unique
                while (sqlRd.Read())
                {
                    PublicParameters.CurrentUser = new Controllers.User();
                    PublicParameters.CurrentUser.FirstName = sqlRd["FirstName"].ToString();
                    PublicParameters.CurrentUser.LastName = sqlRd["LastName"].ToString();
                    PublicParameters.CurrentUser.MailAddress = sqlRd["MailAddress"].ToString();
                    //And other properties to assign
                }

                if(PublicParameters.CurrentUser != null)
                {
                    MessageBox.Show("Login successfully!");
                    //Yo have your logged user 
                }
                else
                {
                    MessageBox.Show("Username or password is incorrect");
                }
            }
        }
    }