我正在寫一個簡單的部分將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
'VALUES([ID],[姓氏],[名字],[地址],[城市])' – Devart
@Devart檢查上面感謝 – Dionisis
編輯'SQLcmd'尚未實例 – Jamiec