我在表中有一个包含消息的列,我希望此消息显示在标签中。这是我的代码,目前没有填充标签。
Protected conString As String = ConfigurationManager.AppSettings("sqldirectory")
Dim cnn As New SqlConnection(conString)
Dim cmd As New SqlCommand("select message from [database].[dbo].[table]")
Dim dr As SqlDataReader
Try
cnn.Open()
dr = cmd.ExecuteReader()
lblMsg.Text = dr(0).ToString
Catch ex As Exception
dr = Nothing
Finally
cnn.Close()
End Try
答案 0 :(得分:1)
好的,在玩完之后,我想出了这个有效的方法
Protected conString As String = ConfigurationManager.AppSettings("sqldirectory")
Dim cnn As New SqlConnection(conString)
Dim cmd As New SqlCommand("select message from [database].[dbo].[table]", cnn)
Dim dr As SqlDataReader
Dim msg As String
Try
cnn.Open()
dr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
While dr.Read()
msg = dr("message")
lblMsg.Text = msg
End While
Catch ex As Exception
dr = Nothing
Finally
cnn.Close()
End Try
答案 1 :(得分:0)
我在寻找别的东西时意外地遇到了这个。有一种更简单的方法可以做到这一点。
我很想创建一些常见的app_code来执行此操作。使用以下代码在项目和common.vb文件中创建app_code文件夹:
Imports Microsoft.VisualBasic
Imports System.Data.SqlClient
Imports System.Data
Namespace GetDBResult
Public Class DB
Public Shared Function GetRecord(sql As String) As String
Dim result As String
Dim connection As New SqlConnection(ConfigurationManager.ConnectionStrings("YourConnectionString").ToString)
connection.Open()
Dim command As New SqlCommand(sql, connection)
Try
If command.ExecuteScalar IsNot System.DBNull.Value Then
result = command.ExecuteScalar
Else
result = ""
End If
Catch ex As Exception
Throw ex
Finally
connection.Close()
End Try
Return result
End Function
End Class
End Namespace
从那里,您可以从任何vb代码调用该函数,从而可以非常轻松地从数据库中获取字段以将其分配给标签。如下:
Dim sql as string = "your sql query which should return one row and column"
label1.text = DB.GetRecord(sql)
节省了大量的重新输入。
哦,请记住在您希望使用app_code的任何视频中导入您的代码
Imports GetDBResult
非常感谢, 尼尔