0

我正在尝试读取 .csv 文件以将其内容导入 SQL 表

我收到错误:

ExecuteReader: Connection property has not been initialized.

在这段代码的最后一行:

Function ImportData(ByVal FU As FileUpload, ByVal filename As String, ByVal tablename As String) As Boolean
Try

    Dim xConnStr As String = "Driver={Microsoft Text Driver (*.txt; *.csv)};dbq=" & Path.GetDirectoryName(Server.MapPath(filename)) & ";extensions=asc,csv,tab,txt;"

    ' create your excel connection object using the connection string
    Dim objXConn As New System.Data.Odbc.OdbcConnection(xConnStr.Trim())
    objXConn.Open()

    Dim objCommand As New OdbcCommand(String.Format("SELECT * FROM " & Path.GetFileName(Server.MapPath(filename)), objXConn))

    If objXConn.State = ConnectionState.Closed Then
        objXConn.Open()
    Else
        objXConn.Close()
        objXConn.Open()
    End If

    ' create a DataReader
    Dim dr As OdbcDataReader
    dr = objCommand.ExecuteReader()
4

3 回答 3

2

您的问题的解决方案如下:

Dim xConnStr As String = "Driver={Microsoft Text Driver (*.txt; *.csv)};dbq=" & Path.GetDirectoryName(Server.MapPath(filename)) & ";extensions=asc,csv,tab,txt;" 

    ' create your excel connection object using the connection string 
    Dim objXConn As New System.Data.Odbc.OdbcConnection(xConnStr.Trim()) 

    Dim objCommand As New OdbcCommand(String.Format("SELECT * FROM " & Path.GetFileName(Server.MapPath(filename)), objXConn)) 

    objCommand.Connection.Open()


    ' create a DataReader 
    Dim dr As OdbcDataReader 
    dr = objCommand.ExecuteReader()

连接被传递给命令,但命令需要打开连接,如上图所示,objCommand.Connection.Open() 因此删除了初始objXconn.Open()

于 2012-07-06T08:02:46.317 回答
0

由于您没有使用 OdbcConnection创建命令,因此您需要在执行命令之前设置命令的Connection 属性:

objCommand.Connection = objXConn
于 2012-06-11T15:21:55.837 回答
0

可能您在调用 ExecuteReader 之前已将其关闭。

//this line has rightly assign the connection to the command
Dim objCommand As New OdbcCommand(String.Format("SELECT * FROM " & Path.GetFileName(Server.MapPath(filename)), objXConn))

但连接必须处于打开状态。你可能在这里以某种方式关闭了它

If objXConn.State = ConnectionState.Closed Then
    objXConn.Open()
Else
    objXConn.Close()
    objXConn.Open()
End If
于 2012-06-11T15:43:35.437 回答