0

我需要从 SQL 查询中收集信息。我正在使用 SQL 数据源控件,因为我将在获取数据后在网格视图中使用它。

我的查询如下所示:[为可读性包装]

SqlDataSource1.SelectCommand = "SELECT [index] AS idex, store_number AS snum, 
    store_name AS sname, store_username AS suser, store_password AS spass, 
    store_count AS scount 
    FROM Stores 
    WHERE store_name = '" & Session("storename") & "'"

非常草率,但希望能满足我的需要。我对变量的了解很少应该意味着索引的字段应该存储到一个名为 idex 的变量中?它是否正确?以后怎么用?

如何从列中获取变量并将其放入文本框之类的内容中,

4

1 回答 1

1

代码的基本结构如下。

打开连接。最好使用Using结构。创建命令(再次,Using结构)。执行命令并获取值。

Dim idx As Integer ' the variable to hold your index

Using conn As SqlConnection = New SqlConnection("your connection string") ' put your connection string here or get it from a config file
    conn.Open()
    Dim commandText As String = "SELECT [index] AS idex, store_number AS snum, store_name AS sname, store_username AS suser, store_password AS spass, store_count AS scount FROM Stores WHERE store_name = @storename"
    Using command As SqlCommand = New SqlCommand(commandText, conn)
        command.Parameters.Add(New SqlParameter("@storename", SqlDbType.VarChar, 50)).Value = "store name" ' replace the store name and the length of the field

        Using reader As SqlDataReader = command.ExecuteReader
            If reader.Read Then
                idx = reader.GetInt32(0) ' the first column
            End If
        End Using
    End Using
End Using

要从配置文件中获取连接字符串,请执行以下操作:

添加对 System.Configuration.dll 的引用

将连接字符串添加到您的配置文件中:

<connectionStrings>
    <add name="YourConnection" connectionString="Details"/>
</connectionStrings>

您可以从代码中获取连接字符串

 Dim connStr As String = System.Configuration.ConfigurationManager.ConnectionStrings("YourConnection").ConnectionString
于 2013-11-06T03:11:59.233 回答