VB.NET 通过表单插入数据
VB.NET insert data via form
我正在尝试将数据插入数据库,但出现错误 ExecuteNonQuery: Connection property has not been initialized.
连接似乎一切正常。
Imports System.Data.SqlClient
Public Class crud1
Private Sub Add_btn_Click(sender As Object, e As EventArgs) Handles Add_btn.Click
Try
Dim conn_ As New SqlConnection("Data Source=DESKTOP-VVM5A31;Initial Catalog=temp;Integrated Security=True")
conn_.Open()
Dim command As New SqlCommand("INSERT INTO STUDENT (student_name, student_age) VALUES (@NAME, @AGE)")
command.Parameters.AddWithValue("@NAME", TXT_NAME.Text)
command.Parameters.AddWithValue("@AGE", Convert.ToInt32(TXT_AGE.Text))
command.ExecuteNonQuery()
MsgBox("Record saved.", MsgBoxStyle.Information)
conn_.Close()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
End Sub
End Class
连接请看图片属性。
你是对的,考虑到命令需要打开连接,然后再执行命令,你做对了。
但是你并没有告诉命令要使用哪个连接。
一个简单的方法是这样的,在执行命令之前:
command.Connection = conn_
我正在尝试将数据插入数据库,但出现错误 ExecuteNonQuery: Connection property has not been initialized.
连接似乎一切正常。
Imports System.Data.SqlClient
Public Class crud1
Private Sub Add_btn_Click(sender As Object, e As EventArgs) Handles Add_btn.Click
Try
Dim conn_ As New SqlConnection("Data Source=DESKTOP-VVM5A31;Initial Catalog=temp;Integrated Security=True")
conn_.Open()
Dim command As New SqlCommand("INSERT INTO STUDENT (student_name, student_age) VALUES (@NAME, @AGE)")
command.Parameters.AddWithValue("@NAME", TXT_NAME.Text)
command.Parameters.AddWithValue("@AGE", Convert.ToInt32(TXT_AGE.Text))
command.ExecuteNonQuery()
MsgBox("Record saved.", MsgBoxStyle.Information)
conn_.Close()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
End Sub
End Class
连接请看图片属性。
你是对的,考虑到命令需要打开连接,然后再执行命令,你做对了。
但是你并没有告诉命令要使用哪个连接。
一个简单的方法是这样的,在执行命令之前:
command.Connection = conn_