我是Visual Studio和SQL Server的新手。我对如何从visual studio应用程序插入数据感到困惑
这是我的代码:
尝试
'===============Add New Patient===================
patient_name = txtName.Text
patient_age = nudAge.Value
date_of_confinement = dtpDate.Value
type_of_sickness = txtSickness.Text
type_of_IVfluid = txtFluid.Text
number_of_bottles = txtBottle.Text
drop_rate = nudDrop.Value
'To check if all values have been filled up
If txtName.Text = "" Or nudAge.Value = "" Or dtpDate.Value = "" _
Or txtSickness.Text = "" Or txtFluid.Text = "" Or txtBottle.Text = "" Or nudDrop.Value = "" _
Then
MsgBox("Please Complete All the Required Fields")
Else
Try
Dim PatientInfoConnection As SqlConnection = New _
SqlConnection("Server=CATH-PC; database=PatientInfoDB;user id=sa;password=*******") 'connection to SQL database
PatientInfoConnection.Open() 'open database connection
Dim sql As String = ""
sql = "insert into model (name, age, date_of_confinement,type_of_sickness, type_of_IVfluid, number_of_bottles, drop_rate)" & _
" values (@txtName.Text, @nudAge.Value, @dtpDate.Value, @txtSickness.Text, @txtFluid.Text, @txtBottle.Text, @nudDrop.Value)"
Dim insert As New SqlCommand(sql, PatientInfoConnection)
insert.Parameters.AddWithValue(patient_name, @txtName.Text)'@ error
insert.Parameters.AddWithValue("val2", nudAge.Value) 'error
insert.Parameters.AddWithValue(Name, patient_name) 'not sure
insert.ExecuteNonQuery()
MsgBox("Successfully Saved")
Me.Visible = False
Mainform.Show()
Catch myerror As MySqlException
MessageBox.Show("Error Connecting to Database: " & myerror.Message & ". Please contact the operator")
End Try
End If
Catch ex As Exception
End Try
我不确定SqlCommand
,因为我不知道如何将用户的输入保存到我的数据库。我想将在文本框中输入的值添加到我的数据库
Dim insert As New SqlCommand(sql, PatientInfoConnection)
insert.Parameters.AddWithValue(patient_name, @txtName.Text) 'error @ char is not valid
insert.Parameters.AddWithValue("val2", nudAge.Value) 'error
insert.Parameters.AddWithValue(Name, patient_name) 'not error but not sure
name(text,null)
是我在SQL Server Management Studio中设计的数据库的一列
请帮帮我。任何帮助,将不胜感激。谢谢!
我改变了insert.Parameters.AddWithValue("@name", txtName.Text)
和sql =“插入到模型部分中,但是我收到了错误
“类型'System.InvalidCastException'的第一次机会异常 发生在Microsoft.VisualBasic.dll“
我很困惑
答案 0 :(得分:2)
你很亲密。
只尝试一个变量名称,然后匹配它们。
所以SQL将是:
sql = "insert into model (name, age, date_of_confinement,type_of_sickness, type_of_IVfluid, number_of_bottles, drop_rate)" & _
" values (@name, @age, @dateOfConfinement, @sicknessType, @fluidType, @bottleAmount, @dropRate)"
然后设置参数:
insert.Parameters.AddWithValue("@name", txtName.Text)