Share via

在C#中查询SQLServer的中数据表中的信息

KerryZY 1 Reputation point
Oct 24, 2022, 7:57 AM

我想实现这样一个功能:
在我用Windows Forms窗体界面验证用户登录信息时,想从我SQLServer服务器的数据库中的一张数据表查询有没有这个用户的相关信息,如果有,则在消息框中提示有这个人;如果没有,则在消息框中说没有这个人。
注:使用的SQLServer版本为2019,使用的代码编辑器为Visual Studio 2019,在Visual Studio中已连接此服务器。253369-%E6%8D%95%E8%8E%B7.png

非常感谢帮助。

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,903 questions
Azure SQL Database
{count} votes

2 answers

Sort by: Most helpful
  1. Bjoern Peters 8,881 Reputation points
    Oct 24, 2022, 11:43 AM

    Hi @KerryZY

    first this is an English spoken/written forum, it would be nice if you could write your question in English.

    second - my translator said - you want to implement a Form and want to get some information from this SQL Server...

    For example you could use this tutorial for connecting your application to SQL Server and grep those information:
    https://www.c-sharpcorner.com/UploadFile/5d065a/tutorial-1sql-server-database-connection-in-window-form/

    If this is not your plan, then tell us more details about your question/problem.


  2. Jiale Xue - MSFT 46,876 Reputation points Microsoft Vendor
    Oct 25, 2022, 9:11 AM

    Hi @KerryZY , Welcome to Microsoft Q&A.

    Please refer to the same question I replied in Stack overflow.

    Simple login and verification

    Edit:

    private void Button1_Click(object sender, EventArgs e)   
    {  
        //Personal test database  
        string myconn = "your conn";  
        SqlConnection conn = new SqlConnection(myconn);  
        string sql= $"select * from Test.dbo.demoAccount where userid=@UserId";  
            try  
            {  
            conn.Open();  
            SqlCommand sqlCommand = new SqlCommand(sql, conn);  
            sqlCommand.Parameters.Add("@UserId", SqlDbType.VarChar, 8).Value = AccountTb.Text.Trim();      
            SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();  
            if (sqlDataReader.HasRows) //Satisfy the user name , enter the next interface  
            {  
                MessageBox.Show("There is this person.");  
            }   
            else  
            {  
               MessageBox.Show("There is no such person");  
            }  
      
            conn.Close();  
        }   
        catch (Exception o)  
        {  
            MessageBox.Show(o.ToString());  
        }  
    }  
    

    Best Regards,
    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.