将数据从SQL数据库检索到VB.NET

时间:2013-03-07 10:34:31

标签: sql vb.net

有谁能告诉我这里我做错了什么? 非常基本的Visual Basic体验。

我试图从提供的数据库中检索ORDERID,ORDERDATE和CUSTOMERID并在dataGridView中显示它们?

Dim con1 As New OleDbConnection
con1.ConnectionString = _
"Provider=msdaora;Data Source=orabis;User Id=112221800;Password=112221800;"

'Dim con1 As New SqlConnection("Provider=msdaora;Data Source=orabis;User Id=112221800;Password=112221800;")
con1.Open()
Dim cmd1 As New SqlCommand("select ORDERID, ORDERDATE AND CUSTOMERID from CUSORDER", con1)

Dim ada1 As New SqlDataAdapter(cmd1)
Dim ds1 As New DataSet
ada1.Fill(ds1)
ViewDeliverys.DataGridView1.DataSource = ds1.Tables(0)

con1.Close()

2 个答案:

答案 0 :(得分:1)

您不能将OleDbConnectionSqlCommand(SQL-Server)一起使用。您使用的是哪个rdbms?

这适用于SQL-Server:

Using con = New SqlConnection(connectionString)
    Using da = New SqlDataAdapter("SELECT ORDERID, ORDERDATE AND CUSTOMERID from CUSORDER", con)
        Dim table = New DataTable()
        da.Fill(table)
        ViewDeliverys.DataGridView1.DataSource = table
    End Using
End Using

编辑:这是OleDb版本:

Using con = New OleDbConnection(connectionString)
    Using da = New OleDbDataAdapter("SELECT ORDERID, ORDERDATE AND CUSTOMERID from CUSORDER", con)
        Dim table = New DataTable()
        da.Fill(table)
        ViewDeliverys.DataGridView1.DataSource = table
    End Using
End Using

答案 1 :(得分:0)

您使用的是SQL Sever或MS Access的数据库? 如果您正在使用SQL Server,请在MS Access上使用SQL Connection,然后使用OleDBConnection。

对于正确的连接字符串,请检查它:

http://www.connectionstrings.com

另请参阅本教程:

http://vb.net-informations.com/ado.net-dataproviders/ado.net-sqldataadapter

并替换您的查询:

Dim cmd1 As New SqlCommand("select ORDERID, ORDERDATE AND CUSTOMERID from CUSORDER", con1)

ORDERDATE AND CUSTOMERID会引发错误

将其更改为:

Dim cmd1 As New SqlCommand("select ORDERID, ORDERDATE,CUSTOMERID from CUSORDER", con1)