检查SQL dB中是否存在值时出现对象引用错误

时间:2014-04-29 22:32:33

标签: sql vb.net

我正在尝试对TextBox1运行一系列检查,并在不满足条件时显示错误消息。最终,在我完成所有条件之前,然后执行表插入并打开文件对话框。

第一个陈述是检查是否有值

第二次检查没有使用数字

第三个检查SQL dB以确保该值尚未使用 - 我在这里遇到了问题。

如果dB中存在该值,则标记正确的错误:

MessageBox.Show(TextBox1.Text & " exists already.")

我的问题是,当不满足该条件时,我收到系统错误:

“对象引用未设置为对象的实例。”

对于这行代码。

Dim tarrif As String = cmd.ExecuteScalar().ToString()

我不确定为什么因为其余代码低于ELSE语句?

以下是我的代码的较长部分,以提供上下文。

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click


    'Checks something is in Textbox1
    If TextBox1.Text.Trim.Length = 0 Then
        MessageBox.Show("Please specify new tarrif name!", "Indigo Billing", _
        MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
    Else
        'Check textbox on only has characters

        If System.Text.RegularExpressions.Regex.IsMatch(TextBox1.Text, "^[0-9]*$") Then


            'Error is box contains numbers
            MessageBox.Show("Please enter Characters only!", "Indigo Billing", _
       MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Else

            'Check name is not already in use

            Using conn As New SqlClient.SqlConnection("server=barry-laptop\SQLEXPRESS; database=Test; integrated security=yes")
                Using cmd As SqlClient.SqlCommand = conn.CreateCommand()

                    cmd.CommandText = "SELECT 1 FROM Tarrifs WHERE Tarrif = @Tarrif"
                    cmd.Parameters.AddWithValue("@Tarrif", TextBox1.Text)
                    conn.Open()

                    Dim tarrif As String = cmd.ExecuteScalar().ToString()
                    If tarrif = "1" Then

                        MessageBox.Show(TextBox1.Text & " exists already.")

                    Else
                        'Create new table based on specified Tarrif name
                        Using con = New SqlConnection("server=barry-laptop\SQLEXPRESS; database=Test; integrated security=yes")
                            Using cmda = New SqlCommand("CREATE TABLE " & TextBox1.Text & " (CallType VarChar(30),ChargeCode VarChar(30),Destination VarChar(30),TariffUsed VarChar(30),Peak Float,OffPeak Float,Weekend Float,Setup Float,MinimumCharge Float,ChargeCap INT,InitialUnits INT,InitialCharge INT,InitialPeak INT,InitialOffPeak INT,InitialWeekend INT,BillingUnit INT,MinimumUnits INT,RateType VarChar(30));", con)
                                con.Open()
                                cmda.ExecuteNonQuery()
                                con.Close()
                            End Using

                            'import name into Tarrif table
                            Using cmdb = New SqlCommand("INSERT INTO Tarrifs (Tarrif) VALUES (@tarrif2)", con)
                                con.Open()
                                cmdb.Parameters.AddWithValue("@tarrif2", TextBox1.Text)
                                cmdb.ExecuteNonQuery()
                                con.Close()
                            End Using
                        End Using


                        '--First create a datatable with the same cols as CSV file, the cols order in both should be same
                        Dim table As New DataTable()

                        table.Columns.Add("CallType", GetType(String))
                        table.Columns.Add("ChargeCode", GetType(String))
                        table.Columns.Add("Destination", GetType(String))
                        table.Columns.Add("TariffUsed", GetType(String))
                        table.Columns.Add("Peak", GetType(Decimal))
                        table.Columns.Add("OffPeak", GetType(Decimal))
                        table.Columns.Add("Weekend", GetType(Decimal))
                        table.Columns.Add("Setup", GetType(Decimal))
                        table.Columns.Add("MinimumCharge", GetType(Decimal))
                        table.Columns.Add("ChargeCap", GetType(Integer))
                        table.Columns.Add("InitialUnits", GetType(Integer))
                        table.Columns.Add("InitialCharge", GetType(Integer))
                        table.Columns.Add("InitialPeak", GetType(Integer))
                        table.Columns.Add("InitialOffPeak", GetType(Integer))
                        table.Columns.Add("InitialWeekend", GetType(Integer))
                        table.Columns.Add("BillingUnit", GetType(Integer))
                        table.Columns.Add("MinimumUnits", GetType(Integer))
                        table.Columns.Add("RateType", GetType(String))



                        'open file dialog and store filename'
                        Dim openFileDialog1 As New OpenFileDialog
                        Dim strFileName As String

如果有人可以帮助解决这个问题,我将非常感激

3 个答案:

答案 0 :(得分:4)

Dim tarrif As String = cmd.ExecuteScalar().ToString()

问题是如果没有返回结果,则cmd.ExecuteScalar()将返回Nothingcmd.ExecuteScalar().ToString()将引发异常。

更好的选择是:

cmd.CommandText = "SELECT 1 FROM Tarrifs WHERE Tarrif = @Tarrif"
cmd.Parameters.AddWithValue("@Tarrif", TextBox1.Text)
conn.Open()

If cmd.ExecuteScalar() Is Not Nothing Then

答案 1 :(得分:0)

如果@tariff与表中的任何值都不匹配,则查询将返回Null。这可能是问题所在。只是一个猜测 - 没有测试过。也许只需将查询更改为

SELECT isNull(TarrifId,0) FROM Tarrifs WHERE Tarrif = @Tarrif

答案 2 :(得分:-2)

尝试使用"尝试捕捉"

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Try

            'Checks something is in Textbox1
            If TextBox1.Text.Trim.Length = 0 Then
                MessageBox.Show("Please specify new tarrif name!", "Indigo Billing", _
                MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Else
                'Check textbox on only has characters

                If System.Text.RegularExpressions.Regex.IsMatch(TextBox1.Text, "^[0-9]*$") Then


                    'Error is box contains numbers
                    MessageBox.Show("Please enter Characters only!", "Indigo Billing", _
               MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                Else

                    'Check name is not already in use

                    Using conn As New SqlClient.SqlConnection("server=barry-laptop\SQLEXPRESS; database=Test; integrated security=yes")
                        Using cmd As SqlClient.SqlCommand = conn.CreateCommand()

                            cmd.CommandText = "SELECT 1 FROM Tarrifs WHERE Tarrif = @Tarrif"
                            cmd.Parameters.AddWithValue("@Tarrif", TextBox1.Text)
                            conn.Open()

                            Dim tarrif As String = cmd.ExecuteScalar().ToString()
                            If tarrif = "1" Then

                                MessageBox.Show(TextBox1.Text & " exists already.")

                            Else
                                'Create new table based on specified Tarrif name
                                Using con = New SqlConnection("server=barry-laptop\SQLEXPRESS; database=Test; integrated security=yes")
                                    Using cmda = New SqlCommand("CREATE TABLE " & TextBox1.Text & " (CallType VarChar(30),ChargeCode VarChar(30),Destination VarChar(30),TariffUsed VarChar(30),Peak Float,OffPeak Float,Weekend Float,Setup Float,MinimumCharge Float,ChargeCap INT,InitialUnits INT,InitialCharge INT,InitialPeak INT,InitialOffPeak INT,InitialWeekend INT,BillingUnit INT,MinimumUnits INT,RateType VarChar(30));", con)
                                        con.Open()
                                        cmda.ExecuteNonQuery()
                                        con.Close()
                                    End Using

                                    'import name into Tarrif table
                                    Using cmdb = New SqlCommand("INSERT INTO Tarrifs (Tarrif) VALUES (@tarrif2)", con)
                                        con.Open()
                                        cmdb.Parameters.AddWithValue("@tarrif2", TextBox1.Text)
                                        cmdb.ExecuteNonQuery()
                                        con.Close()
                                    End Using
                                End Using
       Catch ex as Exception
       Msgbox("Null reference")
    end try


                                '--First create a datatable with the same cols as CSV file, the cols order in both should be same
                                Dim table As New DataTable()

                                table.Columns.Add("CallType", GetType(String))
                                table.Columns.Add("ChargeCode", GetType(String))
                                table.Columns.Add("Destination", GetType(String))
                                table.Columns.Add("TariffUsed", GetType(String))
                                table.Columns.Add("Peak", GetType(Decimal))
                                table.Columns.Add("OffPeak", GetType(Decimal))
                                table.Columns.Add("Weekend", GetType(Decimal))
                                table.Columns.Add("Setup", GetType(Decimal))
                                table.Columns.Add("MinimumCharge", GetType(Decimal))
                                table.Columns.Add("ChargeCap", GetType(Integer))
                                table.Columns.Add("InitialUnits", GetType(Integer))
                                table.Columns.Add("InitialCharge", GetType(Integer))
                                table.Columns.Add("InitialPeak", GetType(Integer))
                                table.Columns.Add("InitialOffPeak", GetType(Integer))
                                table.Columns.Add("InitialWeekend", GetType(Integer))
                                table.Columns.Add("BillingUnit", GetType(Integer))
                                table.Columns.Add("MinimumUnits", GetType(Integer))
                                table.Columns.Add("RateType", GetType(String))



                                'open file dialog and store filename'
                                Dim openFileDialog1 As New OpenFileDialog
                                Dim strFileName As String