vb.net 从数据库读取并填充DataTable
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10844358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read from database and fill DataTable
提问by Bramenath
I'm getting a set of data by a DataReader
and assigning to a string. Now I need to fill the DataTable
columns with the query fields. The DataTable
is connected to a grid to display the filled data.
我通过 a 获取一组数据DataReader
并分配给一个字符串。现在我需要DataTable
用查询字段填充列。将DataTable
被连接到电网以显示填充数据。
query is :
查询是:
strSQL = "SELECT EmpCode,EmpID,EmpName FROM dbo.Employee
DataTable
columns are EmpCode, EmpID, EmpName
.
DataTable
列是EmpCode, EmpID, EmpName
.
I need to read the query and assign to the columns of DataTable
and fill the table. I have tried as below but i dont get the proper output,
我需要阅读查询并分配给表的列DataTable
并填充表。我试过如下,但我没有得到正确的输出,
Me.DtShifts.Tables("NonAllocated").Clear()
Me.DtShifts.Tables("NonAllocated").Load(dr)
回答by SSS
Connection object is for illustration only. The DataAdapter is the key bit:
连接对象仅用于说明。DataAdapter 是关键位:
Dim strSql As String = "SELECT EmpCode,EmpID,EmpName FROM dbo.Employee"
Dim dtb As New DataTable
Using cnn As New SqlConnection(connectionString)
cnn.Open()
Using dad As New SqlDataAdapter(strSql, cnn)
dad.Fill(dtb)
End Using
cnn.Close()
End Using
回答by Snookger Isolation
Private Function LoaderData(ByVal strSql As String) As DataTable
Dim cnn As SqlConnection
Dim dad As SqlDataAdapter
Dim dtb As New DataTable
cnn = New SqlConnection(My.Settings.mySqlConnectionString)
Try
cnn.Open()
dad = New SqlDataAdapter(strSql, cnn)
dad.Fill(dtb)
cnn.Close()
dad.Dispose()
Catch ex As Exception
cnn.Close()
MsgBox(ex.Message)
End Try
Return dtb
End Function