'Object of instance not set to an instance or an object. Visual Basic
I am writing a simple piece to insert 5 values into my local database. The connection gets established well but when I press the button , which does the job for inserting into the DB I get "Object of instance not set to an instance or an object" this message.
Sql version Microsoft SQL Server 2014 - 12.0.2000.8 (X64)
Here is My code
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
Solution 1:[1]
This should work for you:
SQLcmd.CommandText = ("INSERT INTO students([student_ID], [LastName],
[FirstName],[Address],[City]) VALUES({1},'{2}','{3}','{4}','{5}'"),LastName
,firstName,Address,city)
BUT you will be prone to SQL Injection. The correct way to do this is described here and it's name is by using SQL Parameters
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | S.Karras |
