我一直在寻找解决方案,但是找不到。
我在这里也指的是 Getting error System.Data.SqlClient.SqlException: 'Must declare the scalar variable "@EmployeeId".'
但是它似乎也没有解决方案。
我一直有错误 System.Data.SqlClient.SqlException:'必须声明标量变量“ @DocID”。'
我的SQL表
[DoctorID] NVARCHAR (5) NOT NULL,
[Name] NVARCHAR (50) NULL,
[Gender] NVARCHAR (10) NULL,
[Email] NVARCHAR (30) NULL,
[Username] NVARCHAR (10) NULL,
[Password] NVARCHAR (10) NULL,
PRIMARY KEY CLUSTERED ([DoctorID] ASC)
);
INSERTDATA
Public Function insertdata(ByVal qr As String) As Integer
cmd = New SqlCommand(qr, con)
con.Open()
i = cmd.ExecuteNonQuery()
con.Close()
Return i
End Function
我的密码
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim qr As String
cmd.Parameters.AddWithValue("@DoctorID", txtDocID.Text)
cmd.Parameters.AddWithValue("@Name", txtName.Text)
cmd.Parameters.AddWithValue("@Gender", cboGender.Text)
cmd.Parameters.AddWithValue("@Email", txtEmail.Text)
cmd.Parameters.AddWithValue("@Username", txtUsername.Text)
cmd.Parameters.AddWithValue("@Password", txtPassword.Text)
qr = "INSERT INTO Doctor (DoctorID, Name, Gender, Email, Username, Password) Values (@DoctorID, @Name, @Gender, @Email, @Username, @Password)"
Dim logincorrect As Boolean = Convert.ToBoolean(insertdata(qr))
If (logincorrect) Then
MsgBox("Record Inserted Successfully", MsgBoxStyle.Information)
Else
MsgBox("Something Wrong, Record Not Saved.", MsgBoxStyle.Critical)
End If
disp_data()
End Sub
该如何解决?
答案 0 :(得分:1)
如果将数据库对象保留在使用方法所在的本地,则可以避免很多麻烦。
您正在将查询字符串传递到insertdata
函数,然后创建一个New
命令。此新命令对添加按钮中要添加参数的命令一无所知。
用于参数的.Add
方法优于.AddWithValue
。参见http://www.dbdelta.com/addwithvalue-is-evil/
和
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
还有一个:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
这是另一个
https://andrevdm.blogspot.com/2010/12/parameterised-queriesdont-use.html
公开.Dispose
方法的数据库对象不仅需要关闭,而且还需要处置,因为它们可能包含不受管的代码。 Using...End Using
块即使有错误也可以为您解决这个问题。
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim rowsInserted As Integer
Using cn As New SqlConnection("Your connection string."),
cmd As New SqlCommand("INSERT INTO Doctor (DoctorID, Name, Gender, Email, Username, Password) Values (@DoctorID, @Name, @Gender, @Email, @Username, @Password);", cn)
With cmd.Parameters
.Add("@DoctorID", SqlDbType.NVarChar, 5).Value = txtDocID.Text
.Add("@Name", SqlDbType.NVarChar, 50).Value = txtName.Text
.Add("@Gender", SqlDbType.NVarChar, 10).Value = cboGender.Text
.Add("@Email", SqlDbType.NVarChar, 30).Value = txtEmail.Text
.Add("@Username", SqlDbType.NVarChar, 10).Value = txtUsername.Text
.Add("@Password", SqlDbType.NVarChar, 10).Value = txtPassword.Text
End With
cn.Open()
rowsInserted = cmd.ExecuteNonQuery
End Using
If rowsInserted = 1 Then
MsgBox("Record Inserted Successfully", MsgBoxStyle.Information)
Else
MsgBox("Something Wrong, Record Not Saved.", MsgBoxStyle.Critical)
End If
disp_data()
End Sub