2011-10-09 59 views
0

我正在使用下面的代碼在表中插入數據,並且我在cmd.executenonquery()上得到錯誤....異常被標記作爲SQL異常和底層消息說「字符串或二進制數據將被截斷,該語句已被終止。」使用vb.net在sql server數據庫中插入數據時出錯

 Dim str As String ' defines str as a string variable 

     'takes insertion query as a string in str variable 
     str = "Insert into Instructors Values(@inst_id, @inst_name, @contact, @game, 'N/A', 'N/A', 'Available')" 

     'defines a new command which takes query string and connection string as parameters 
     Dim cmd As New SqlCommand(str, con) 

     ' defines Instructor ID parameter and takes its value from the form 
     Dim prmInstID As New SqlParameter("@inst_id", SqlDbType.Int) 
     prmInstID.Value = TxtInstID.Text 

     ' defines Instructor Name parameter and takes its value from the form 
     Dim prmInstName As New SqlParameter("@inst_name", SqlDbType.Char) 
     prmInstName.Value = TxtInstName.Text 

     ' defines Contact parameter and takes its value from the form 
     Dim prmContact As New SqlParameter("@contact", SqlDbType.VarChar) 
     prmContact.Value = MskdTxtCntctno.Text 


     ' defines Specialty Game parameter and takes its value from the form 
     Dim prmGame As New SqlParameter("@game", SqlDbType.VarChar) 
     prmGame.Value = Me.ComboBox1.SelectedItem 

     cmd.Parameters.Add(prmInstID) 
     cmd.Parameters.Add(prmInstName) 
     cmd.Parameters.Add(prmContact) 
     cmd.Parameters.Add(prmGame) 


     cmd.ExecuteNonQuery() 

     con.Close() 
+0

你用'TxtInstID.Text','TxtInstName.Text','MskdTxtCntctno.Text'和'Me.ComboBox1.SelectedItem'測試了什麼值? –

回答

0

如果數據庫中的文本字段太小而不適合要插入的數據,則通常會發生此異常。例如,如果數據庫中的教師姓名字段長度爲10(字符),而TxtInstName.Text中的文字長度超過10個字符,則會出現此錯誤。

要解決此問題,您可以使數據庫中的字段更大或在表單內檢查文本不太長。

0

正如aKzen所說,錯誤信息可能是因爲您試圖插入太長的東西以適合您的某個字段。

我只是認爲我會添加到這一些指針,因爲我會假設你還在學習等等。如果你使用存儲過程,你可以減少很多代碼,並且還可以提高應用程序的效率。

存儲過程給你一些好處,它們更安全,因爲你不通過網絡傳輸查詢(如果有人攔截你的查詢,他們可以獲得關於你的表結構的知識)存儲過程不必每次重新編譯它們的執行時間與傳遞查詢字符串的時間不同,因爲服務器在每次收到查詢時都必須編譯查詢。同樣,使用SP可以在多個位置重複使用相同的查詢,而無需複製粘貼queryString。

以下是我寫寫代碼的方法。

' Declare a new command 
Dim cmd As New SqlCommand 

' Set the type to Stored Proc and Tell it which connection to use 
cmd.CommandType = CommandType.StoredProcedure 
cmd.CommandText = "spMySpNameGoesHERE" 
cmd.Connection = con 

' Add the parameter and its value 
cmd.Parameters.AddWithValue("@ParamName",TxtInstID.Text) 
' More Params go here 

cmd.ExecuteNonQuery() 

con.Close() 


CREATE PROCEDURE spMySpNameGoesHERE 
(
@inst_id INT, 
@inst_name VARCHAR(50), 
etc etc 
) 
AS 
BEGIN 

Insert into 
Instructors 
Values(@inst_id, @inst_name, @contact, @game, 'N/A', 'N/A', 'Available')   

END 
0

此錯誤是因爲您在一個或多個字段中輸入的字符數大於數據庫表列的大小。

例如,如果您在具有VARCHER(10)數據類型和長度的表中具有名稱列。 如果您在名稱欄中輸入了10個以上的字符,那麼您將收到此錯誤。

解決方案: 增加列的長度。例如25或滿足您的要求。 和 限制文本框中字符數MaxLength="25"如果是文本框。

相關問題