2016-02-05 64 views
0

我正在运行过程中出现读者循环内部这段代码:vb.net读取MySQL表列问题上没有什么字段类型在MySQL

While reader.read 
For x = 0 To reader.FieldCount - 1 
    MsgBox(reader.GetValue(x)) 
    Dim find_text As String = "<<" & reader.GetName(x) & ">>" 
    Dim replacet_text As String = reader.GetString(x) 

    oDoc.Content.Find.Execute(FindText:=find_text, ReplaceWith:=replacet_text, Replace:=word.WdReplace.wdReplaceAll) 
Next 
End While 

所以其显示每列作为我的SQL查询说SELECT * from table1

但问题是,根据数据库中的列的类型,它显示错误,如cannot be converted to type 'String'.

无论什么类型,我该怎么办?我只是想全部读入一个字符串

回答

1

尝试Dim replacet_text As String = reader.GetValue(x).ToString如果它失败了,这意味着类型不能转换为字符串,所以你可以将这一行代码放在try catch块中,并在数据不可转换时放置错误消息字符串:

While reader.read 
For x = 0 To reader.FieldCount - 1 
    MsgBox(reader.GetValue(x)) 
    Dim find_text As String = "<<" & reader.GetName(x) & ">>" 
    Dim replacet_text As String 
    Try 
     replacet_text = reader.GetValue(x).ToString() 
    Catch ex As Exception 
     replacet_text = "-- Not Available! --" 
    End Try 
    oDoc.Content.Find.Execute(FindText:=find_text, ReplaceWith:=replacet_text, Replace:=word.WdReplace.wdReplaceAll) 
Next 
End While 
+0

有没有一种方法可以检查循环中的列的类型? – charlie

+0

是的,您可以使用'reader.GetSchemaTable()'函数访问另一个名为'Schema Table'的DataTable中所请求表类型的信息。模式表中的第一列(索引0)应该是您的字段名称,第二列将是类型。模式表中的行数等于表定义的字段数。 –