空值错误 - 将数据插入SQl数据库

时间:2017-06-24 16:25:25

标签: sql-server wpf vb.net

我正在尝试连接到SQL数据库并读取/写入数据。一些上下文 - Visual Studio 2015,Windows 10,通过VPN连接到SQL Server 2005,使用ADO.Net 4.1。我的代码如下:

Imports System.Data.SqlClient

Class MainWindow

Dim con As New SqlConnection
Dim cmd As New SqlCommand


Private Sub btn_WriteInt_Click(sender As Object, e As RoutedEventArgs) Handles btn_WriteInt.Click

    Try
        'Establish connection to SQL Database
        con.ConnectionString = "Data Source=serverIP;Initial Catalog=mydatabase;Persist Security Info=True;User ID=user;Password=password"
        con.Open()
        cmd.Connection = con
        'Save data to table
        Dim int_IntTest As Integer = Int(txt_IntTest.Text)
        cmd.CommandText = "INSERT INTO tbl_SQLTest([IntTest]) VALUES('" & txt_IntTest.Text & "')"
        cmd.ExecuteNonQuery()

    Catch ex As Exception
        MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
    Finally
        con.Close()
    End Try

End Sub

Private Sub btn_TestInt_Click(sender As Object, e As RoutedEventArgs) Handles btn_TestInt.Click
    Dim int_IntTest As Integer = Int(txt_IntTest.Text)
    MsgBox(int_IntTest)
End Sub
End Class

SQL Server表如下所示:tbl_SQLTest

当我运行应用程序时,在txt_IntTest中输入“2”并单击btn_WriteInt,我收到以下错误:

Error Message]

2 个答案:

答案 0 :(得分:2)

如果未在“StringTest”中添加值,则在表中插入新行时,会添加null,因此您需要执行以下操作之一:

  • 在此表中为此列提供null,
  • 在查询中传递空值。
  • ''列中添加默认StringTest

答案 1 :(得分:0)

根据接受的答案(我认为是正确的答案,我赞成)。我建议你做这样的事情:

cmd.CommandText = "INSERT INTO tbl_SQLTest([IntTest], [StringTest) VALUES(@intTest, @stringTest)"

cmd.Parameters.AddWithValue("@intTest", Int(txt_IntTest.Text))
cmd.Parameters.AddWithValue("@stringTest", "")

cmd.ExecuteNonQuery()