2016-02-26 276 views
-1

我正在寫一個簡單的部分將5個值插入到本地數據庫中。連接建立得很好,但是當我按下按鈕時,插入到數據庫中的作業會得到「實例對象未設置爲實例或對象」此消息。未設置爲實例或對象的實例對象。 Visual Basic

版本的SQL 的Microsoft SQL Server 2014 - 12.0.2000.8(X64)

這裏是我的代碼

Imports System.Data.Sql 
Imports System.Data.SqlClient 

Public Class Form1 
Dim ID As Integer = 0 

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 

    Dim SQLCon As New SqlConnection With {.ConnectionString = "Server=DIONISIS-PC\SQLEXPRESS; Database=Testing;Trusted_Connection=True;" 
             } 
    Dim SQLcmd As SqlCommand 
    Try 
     SQLCon.Open() 
     Label2.Text = "Connected" 


    Catch ex As Exception 
     Label2.Text = "ERROR" 
     MsgBox(ex.Message) 

    Finally 
     SQLCon.Close() 

    End Try 

End Sub 

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
    Dim SQLCon As New SqlConnection With {.ConnectionString = "Server=DIONISIS-PC\SQLEXPRESS; Database=Testing;Trusted_Connection=True;" 
             } 
    Dim SQLcmd As SqlCommand 
    ID += 1 
    Dim LastName As String = TextBox1.Text 
    Dim firstName As String = TextBox2.Text 
    Dim Address As String = TextBox3.Text 
    Dim city As String = TextBox4.Text 
    Try 
     SQLCon.Open() 
     SQLcmd.Connection = SQLCon 'EDIT: The problem seems to be here' 
     SQLcmd.CommandText = "INSERT INTO students([student_ID], [LastName],[FirstName],[Address],[City]) VALUES([ID], [LastName],[firstName],[Address],[city])" 
     SQLcmd.ExecuteNonQuery() 



    Catch ex As Exception 

     MsgBox(ex.Message) 

    Finally 
     SQLCon.Close() 

    End Try 

End Sub 
End Class 
+0

'VALUES([ID],[姓氏],[名字],[地址],[城市])' – Devart

+0

@Devart檢查上面感謝 – Dionisis

+0

編輯'SQLcmd'尚未實例 – Jamiec

回答

-1

您需要在嘗試設置屬性之前實例化SQLcmd

1

這應該爲你工作:

SQLcmd.CommandText = ("INSERT INTO students([student_ID], [LastName],  
[FirstName],[Address],[City]) VALUES({1},'{2}','{3}','{4}','{5}'"),LastName  
,firstName,Address,city) 

你將會傾向於SQL注入。正確的方法是here,它的名稱是通過使用SQL參數

+0

以及它沒有工作......似乎這條線有問題。 SQLcmd.Connection = SQLCon – Dionisis

相關問題