我在vb.net中执行数据读取器命令时遇到错误。它抛出处理。此字段就像您在文本框中输入员工ID一样,然后它将在数据库中捕获其他字段名称,部门。
这是我的代码
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim conn As New MySql.Data.MySqlClient.MySqlConnection
Dim strConnectionString As String =ConfigurationManager.ConnectionStrings("testConnectionString").ConnectionString
Dim sqlQuery As String = "SELECT * hr_record WHERE Emplid='" & txt1.Text & "'"
Using sqlConn As New MySqlConnection(strConnectionString)
Using sqlComm As New MySqlCommand()
With sqlComm
.CommandText = sqlQuery
End With
Try
sqlConn.Open()
Dim sqlReader As MySqlDataReader = sqlComm.ExecuteReader()
While sqlReader.Read()
txt1.Text = sqlReader("Emplid").ToString()
TextBox1.Text = sqlReader("Nama").ToString()
TextBox2.Text = sqlReader("DeptDesc").ToString()
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
End Try
End Using
End Using
End Sub
答案 0 :(得分:0)
尝试更改您的选择查询,例如
Dim sqlQuery As String = "SELECT * from hr_record WHERE Emplid='" & txt1.Text & "'"
注意: - 无法使用Page_Load
中的代码。尝试创建一个函数并从Page_Load
调用该函数并始终使用Parameterized query
。 < / p>
更新回答:
<强>的Page_Load 强>
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
DataBind()
End Sub
外部方法:
Public Sub DataBind()
Dim sConnection As String = "server=(local);uid=sa;pwd=PassWord;database=DatabaseName"
Using Con As New MySqlConnection(sConnection)
Con.Open()
Using Com As New MySqlCommand("SELECT * from hr_record WHERE Emplid='"txt1.Text
"'", Con)
Using RDR = Com.ExecuteReader()
If RDR.HasRows Then
Do While RDR.Read
txt1.Text = RDR.Item("Emplid").ToString()
TextBox1.Text = RDR.Item("Nama").ToString()
TextBox2.Text = RDR.Item("DeptDesc").ToString()
Loop
End If
End Using
End Using
Con.Close()
End Using
End Sub
注意:尝试实现这样的逻辑,并根据您的要求进行修改。
希望它有效。
答案 1 :(得分:0)
你试图在页面加载中获得Emplid,但你仍然应该使用按钮检查Emplid是否存在
答案 2 :(得分:0)
感谢所有感谢帮助我..最终这个代码感谢所有人。 这个代码将是函数
Dim conn As New MySql.Data.MySqlClient.MySqlConnection
Dim strConnectionString As String = ConfigurationManager.ConnectionStrings("testConnectionString").ConnectionString
Using sqlConn As New MySqlConnection(strConnectionString)
sqlConn.Open()
Using sqlComm As New MySqlCommand()
sqlComm.Connection = sqlConn
With sqlComm
.CommandText = "SELECT * from hr_record WHERE Emplid='" & txt1.Text & "'"
End With
Try
Dim sqlReader As MySqlDataReader = sqlComm.ExecuteReader()
While sqlReader.Read()
txt1.Text = sqlReader("Emplid").ToString()
TextBox1.Text = sqlReader("Nama").ToString()
txtdep.Text = sqlReader("DeptDesc").ToString()
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
End Try
sqlConn.Close()
End Using
End Using
End Sub