从sql返回一个值

本文关键字:一个 sql 返回 | 更新日期: 2023-09-27 18:02:20

我试图将我的sql连接移动到类文件中的一个方法,并返回一个值来检查数据库中是否存在用户名,并在页面中显示为文本以向其他人显示用户名存在。我应该如何修改aspx.cs页面以在aspx代码页中将错误显示为标签?

我在aspx.cs页面上的原始代码:

        string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(connectionString))
        {
            con.Open();
            bool exists = false;
            // create a command to check if the username exists
            using (SqlCommand cmd = new SqlCommand("select count(*) from Member where UserName = @UserName", con))
            {
                cmd.Parameters.AddWithValue("UserName", UNameTxtBox.Text);
                exists = (int)cmd.ExecuteScalar() > 0;
            }
            // if exists, show a message error
            if (exists)
                ExistLabel.Text = "UserName exists";

我的类文件代码:

public static string searchusername(string username)
{
    connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
    SqlConnection conn = new SqlConnection(connectionString);
    {
        conn.Open();
        bool exists = false;
        using (SqlCommand comm = new SqlCommand("select count(*) from Member where UserName = @UserName", conn))
        {
            comm.Parameters.AddWithValue("@username", username);
            exists = (int)comm.ExecuteScalar() > 0;
        }
        if (exists)
        {
            return "exist";
        }
        return null;
    }

我的aspx-cs文件中的代码:

 MemberDB.searchusername(UNameTxtBox.Text);

从sql返回一个值

在页面中添加一个label,并通过方法将标签的Text属性设置为value returned

<asp:Label runat="server" ID="userExists"></asp:Label>

并且比在代码后面做这样的

userExists.Text = MemberDB.searchusername(UNameTxtBox.Text);
public static bool searchusername(string username)
{
    connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
    using(SqlConnection conn = new SqlConnection(connectionString))
    {
        conn.Open();
        bool exists = false;
        using (SqlCommand comm = new SqlCommand("select count(*) from Member where UserName = @UserName", conn))
        {
            comm.Parameters.AddWithValue("@username", username);
            exists = (int)comm.ExecuteScalar() > 0;
        }
        return exists;
    }

在您的页面

if(MemberDB.searchusername(UNameTxtBox.Text))
{
    ExistLabel.Text = "UserName exists";
}