代码的基本结构如下。
打开连接。最好使用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