2012-08-15 19 views
0

插入一個整數到SQLite表內vb.net下面的代碼工作我不能用vb.net

cmd.CommandText = "CREATE TABLE Notes (num INTEGER, name TEXT)" 
Try 
     cmd.ExecuteNonQuery() 
Catch ex As Exception 
     MsgBox("Error during save operation: " & ex.Message) 
End Try 

cmd.CommandText = "insert into Notes(num , name) VALUES(3, 'Bob') " 
Try 
    Console.WriteLine(cmd.ExecuteNonQuery()) 
Catch ex As Exception 
    MsgBox("Error during save operation: " & ex.Message) 
End Try 

但我想提出一個整型變量,而不是插入數字3。我想這一點:

Dim count As Integer = 1 
cmd.CommandText = "insert into Notes(num , name) VALUES(" + count " + , 'Bob') " 

Try 
    Console.WriteLine(cmd.ExecuteNonQuery()) 
Catch ex As Exception 
     MsgBox("Error during save operation: " & ex.Message) 
End Try 

但後來我也有例外:

Conversion from string "insert into Notes(isFirst" to type 'Double' is not valid. 

我知道,行:

"insert into Notes(num , name) VALUES(" + count + ", 'Bob') " 

似乎是完全錯誤的,但我找不到任何其他解決方案,因爲我嘗試了所有。

如何將count變量插入表中?

在此先感謝。

回答

1

您對雙引號的錯誤的一邊 「+」 符號:

cmd.CommandText = "insert into Notes(num , name) VALUES(" + count " + , 'Bob') " 

應該

cmd.CommandText = "insert into Notes(num , name) VALUES(" & count & ", 'Bob') " 

而作爲ChrisStauffer提到,使用的參數。總是。

+0

是的,它的工作原理,謝謝! – Novemberland 2012-08-15 20:57:54

1

您應該參數化查詢。我不確定SQLite的確切語法,因爲我使用的是Oracle,但這肯定會讓您走上正軌。

Dim count As Integer 
'Whatever code you need to get the count from the user. 

cmd.CommandText = "insert into Notes(num , name) VALUES(@count, 'Bob')" 

Dim myParam As New SQLiteParameter("@count") 
cmd.Parameters.Add(myParam) 

'Continue with executing the query, storing the result, etc.