[英]Error `Conversion from string “” to type 'Double' is not valid` in VB.net
[英]vb.net function error conversion from string to type double
我有這個vb.net函數:
Function CheckBillingRun(customer, type, month, year)
Dim conn = New MySqlConnection()
Dim myCommand As New MySqlCommand
Dim reader As MySqlDataReader
Dim SQL As String
Dim result As String
conn.ConnectionString = "server=" + global_variables.web_server_ip + "; user id=" + global_variables.web_server_username + "; password=" + global_variables.web_server_password + "; database=" + global_variables.web_server_database + "; "
conn.Open()
SQL = "SELECT COUNT(sequence) from billing_runs WHERE customer = '" + customer + "' AND type = '" + type + "' AND MONTH(datetime) = '" + month + "' AND YEAR(datetime) = '" + year + "' "
myCommand.Connection = conn
myCommand.CommandText = SQL
reader = myCommand.ExecuteReader
reader.Read()
result = reader.GetString(0)
conn.Close()
Return result
End Function
我試圖使用以下代碼在我的應用程序中調用它:
If CheckBillingRun(reader.GetString(0), "Voice Billing", DateTime.Now.ToString("MM"), DateTime.Now.ToString("yyyy") > 0) Then
Continue While
End If
reader.getstring(0)
等於278
但我收到一條錯誤消息:
Additional information: Conversion from string "SELECT COUNT(sequence) from bill" to type 'Double' is not valid.
VB.NET中的字符串串聯運算符為&或+,但是如果使用+運算符並且為項目設置了Option Strict Off,則可能會出現類似的意外情況。 編譯器知道傳遞給該函數的一個或多個參數不是字符串而是數字,在這種情況下,+運算符會嘗試將所有內容轉換為數字。 嘗試使用&運算符連接字符串。
就是說,不要CONCATENATE字符串來構建sql命令。
使用參數化查詢可以避免Sql Injection和其他解析問題。
例如,您的代碼可能是這樣的
Function CheckBillingRun(ByVal customer as String , ByVale type as String, _
ByVal month as Integer, ByVal year as Integer) as Integer
Dim SQL = "SELECT COUNT(sequence) from billing_runs " & _
"WHERE customer = @customer AND type = @type " & _
"AND MONTH(datetime) = @month AND YEAR(datetime) = @year"
Using conn = New MySqlConnection()
Using myCommand As New MySqlCommand(SQL, conn)
Dim result As Integer = 0
conn.ConnectionString = "......."
conn.Open()
myCommand.Parameters.Add("@customer", MySqlDbType.VarChar).Value = customer
myCommand.Parameters.Add("@type", MySqlDbType.VarChar).Value = type
myCommand.Parameters.Add("@month", MySqlDbType.Int).Value = month
myCommand.Parameters.Add("@year", MySqlDbType.Int).Value = year
Using reader = myCommand.ExecuteReader
if reader.Read() Then
result = reader.GetInteger(0)
End If
End Using
Return result
End Using
End Using
End Function
用它來稱呼它
CheckBillingRun(reader.GetString(0), "Voice Billing", _
DateTime.Now.Month, DateTime.Now.Year)
在此版本中,使用的每個變量都有其類型指定,以避免編譯器可能進行的任何不必要的自動轉換。 還要注意,COUNT返回一個數字,而不是字符串。 像對待字符串一樣對待數字是一個壞習慣,應盡快予以取消。 查看您的項目屬性,然后嘗試將Option Strict設置為ON會發生什么情況
如果方法CheckBillingRun
的第一個參數接受double
,則應使用Convert.ToDouble()
方法將值從string
轉換為double
,如下所示:
相反,如果
If CheckBillingRun(reader.GetString(0), .....
請執行下列操作:
If CheckBillingRun(Convert.ToDouble(reader.GetString(0)), .....
祝一切順利。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.