[英]Read data from SQL Query in 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的变量中? 这个对吗? 以后如何使用?
如何从列中获取变量,然后将其放入文本框等内容中,
该代码的基本结构如下。
打开连接。 最好使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.