我(我自己)学到了一点VBA,现在我试图在VB.net中传输一些代码
要从mySql数据库中提取数据,我改编了这段代码:
Cn.Open("Driver={MySQL ODBC 5.3 Unicode Driver};Server=" & Server_Name & _
";Database=" & Database_Name & ";Uid=" & UserDB & ";Pwd=" & Password & ";")
SQLStr = "SELECT * FROM errlog WHERE Data > NOW()-100000"
rs.CursorLocation = ADODB.CursorLocationEnum.adUseClient
rs.Open(SQLStr, Cn, ADODB.CursorTypeEnum.adOpenStatic)
If rs.RecordCount > 0 Then mRS_Result = rs.GetRows()
If rs.State Then rs.Close()
因此,要循环提取记录列中的所有数据,我通常会这样做:
NumCol = 0
For NumRow = 0 to mRS_Result.GetUpperBound(1)
myValue = mRS_Result(NumCol, NumRow)
Next NumRow
根据收到的建议,我将方法更改为.net方式,现在我正在使用此代码:
cnString = "datasource=" + Server_Name + ";username= " + UserDB + _
";password=" + Password + ";database=" + Database_Name + ""
sqlQRY = "SELECT * FROM errlog WHERE Data > NOW()-100000"
conn = New MySqlConnection(cnString)
Try
conn.Open()
da = New MySqlDataAdapter(sqlQRY, conn)
Dim cb As MySqlCommandBuilder = New MySqlCommandBuilder(da)
da.Fill(ds, "" + TextBox3.Text + "")
Catch ex As Common.DbException
MsgBox(ex.ToString)
Finally
conn.Close()
End Try
因此,要循环提取记录列中的所有数据,我正在使用此代码:
NumCol = 0
For NumRow = 0 to ds.Tables(0).Rows.count -1
myValue = ds.Tables(0).Rows(NumRow ).item(NumCol).tostring
Next NumRow
我的问题是:
这是正确的.net方式吗?
“。ToString”有用吗?当数据是数字时?
答案 0 :(得分:0)
虽然这段代码接口正常(它会按预期编译和工作)但这不是你应该如何使用.NET
我建议有一些改进。
Try obj = ... Finally obj.Dispose() End Try
所以你的代码应该是这样的
Dim connectionString As String = "..."
Dim query as String = "..."
Using ds As DataSet = MySqlHelper.ExecuteDataset(connectionString, query)
For Each row As DataRowView In ds.Tables(0).DefaultView
Dim value As Integer = CType(row("name"), Integer)
' Or if column can be null, use a Nullable<integer>
Dim value As Integer? = If(DBNull.Value.Equals(row("name")), Nothing, CType(row("name"), Integer?))
Next
End Using