从VB.Net中的SQL Query读取数据

时间:2013-11-06 02:23:50

标签: sql sql-server vb.net

我需要从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的变量中?它是否正确?我以后如何使用它?

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

1 个答案:

答案 0 :(得分: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