我正在使用VB 2008 Express Edition,并将四个文本框值传递给数据库。昏暗的陈述写在公共类内部的函数外部。
Imports System.Data.SqlClient
Public Class AddRecord
Dim insertQuery As String
Dim connection As New SqlConnection("Server= DESKTOP-STMQUHM; Database = HospitalDB; Intergrated Security= true")
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
insertQuery="insert into Patient_details(NAME,HOUSENAME,DISTRICT,DISEASE)VALUES('"& RichTextBox1.Text& "','" & RichTextBox2.Text& "','" & RichTextBox3.Text& "',"& RichTextBox8.Text& ")",connection //error line
ExecuteQuery(insertQuery)
MessageBox.Show("Data Inserted")
答案 0 :(得分:0)
这与您要执行的操作有点接近。在线注释和解释。
Private Sub OPCode()
'The Using block will close and dispose of your connection
Using connection As New SqlConnection("Server= DESKTOP-STMQUHM; Database = HospitalDB; Intergrated Security= true")
'Parameters greatly simplifies the query eliminating quotation errors
Dim insertQuery = "insert into Patient_details(NAME,HOUSENAME,DISTRICT,DISEASE)VALUES(@Name, @HouseName, @District, @Disease)"
Dim com As New SqlCommand(insertQuery, connection)
'Why are you using RichTextBoxes instead of TextBoxes?
com.Parameters.Add("@Name", SqlDbType.VarChar).Value = RichTextBox1.Text
com.Parameters.Add("@HouseName", SqlDbType.VarChar).Value = RichTextBox2.Text
com.Parameters.Add("@District", SqlDbType.VarChar).Value = RichTextBox3.Text
com.Parameters.Add("@Disease", SqlDbType.VarChar).Value = RichTextBox4.Text
Try
connection.Open()
com.ExecuteNonQuery()
MessageBox.Show("Data Inserted")
'You will probably want to catch and handled more detailed exceptions
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Sub