简体   繁体   English

使用SQLdatasource进行验证-C#

[英]Validating with SQLdatasource - C#

I am using visual studios 2010, and I have added a database and connected to it with SQLdatasource. 我正在使用Visual Studios 2010,并且已经添加了数据库并通过SQLdatasource连接到该数据库。 I'm creating a basic login. 我正在创建一个基本的登录名。 I want the user to enter the login, and when he tries to login, I want to interate through the database and check if the login name exists. 我希望用户输入登录名,当他尝试登录时,我想遍历数据库并检查登录名是否存在。 How would I select just one column from the database and iterate through it. 我如何只从数据库中选择一列并对其进行遍历。

I guess the select SQL statement will be 我想选择SQL语句将

SELECT userName from tblUser 从tblUser中选择用户名

where username is column and tblUser is the table 其中username是列,tblUser是表

You got the SQL statement right, at the end your SQLDataSource will look something like this: 您正确使用了SQL语句,最后,您的SQLDataSource将如下所示:

<asp:SqlDataSource
          id="SqlDataSource1"
          runat="server"
          DataSourceMode="DataReader"
          ConnectionString="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;"
          SelectCommand="SELECT userName from tblUser">
      </asp:SqlDataSource>

Note: You may want to use a connection string located in your config file: 注意:您可能要使用配置文件中的连接字符串:

 ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"

Also, you could also try to execute this query without using a SQLDataSource since it sounds like you will not be binding the result to a control. 另外,您也可以尝试不使用SQLDataSource来执行此查询,因为听起来您不会将结果绑定到控件。 For example: 例如:

using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        SqlCommand command = new SqlCommand(
            "SELECT userName from tblUser", connection);
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        try
        {
            while (reader.Read())
            {
               // check if reader[0] has the name you are looking for

            }
        }
        finally
        {
            // Always call Close when done reading.
            reader.Close();
        }
    }

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

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