sql-server - 连接字符串属性尚未初始化
问题描述
所以我试图根据我的组合框填充我的文本框,该组合框也链接在我的 sql 服务器中。
每次我在 ComboBox 中选择一个项目时都会出现此错误。
连接字符串属性尚未初始化
Private Sub CBuname_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CBuname.SelectedIndexChanged
Dim cmd As New SqlCommand()
Dim Reader As SqlDataReader
Try
con.Open()
Dim sql As String = "Select * From CoAdminData where Username='" & CBuname.Text & "'"
cmd = New SqlCommand(sql, con)
Reader = cmd.ExecuteReader
If Reader.HasRows() Then
While Reader.Read
txtSID.Text = Reader("StudentID")
txtFirstname.Text = Reader("Firstname")
txtLastname.Text = Reader("Lastname")
End While
End If
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Dispose()
End Try
End Sub
解决方案
只是为了给出一个完整的示例和模板,您可以使用/修改。我已经评论了你需要开始的一切。
与其在公共类中声明 con,不如尝试使用每个方法打开和关闭它。您可以在其他地方公开声明 constr,这样可以节省一些写作时间。Hth
Imports System.Data.SqlClient
Private Sub Template_SQL_Reader()
'Obviously rename SQL with you server, DATABASE with the DB, USERNAME and PASSWORD with your creds too
Dim constr As String = "Server=SQL;Initial Catalog=DATABASE;uid=USERNAME;Pwd='Password'"
Dim con As SqlConnection = New SqlConnection(constr)
'Carefull not to include query string that could allow
'SQL injection (https://en.wikipedia.org/wiki/SQL_injection)
Dim qry As String = "SELECT * FROM TABLE" '<<< Ok - No SQL Injection avaliable
'Dim qry As String = "SELECT * FROM TABLE WHERE FirstName='" & textbox1.text & "'" <<< BAD IDEA SQL Injection Possible !!!!!!
Dim cmd As SqlCommand = New SqlCommand(qry, con)
'Open connection
con.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader
While rdr.Read
'If there are no rows - then nothing will happen, as .read = false
'Do your reading...
End While
'Dispose command
cmd.Dispose()
'close connection
con.Close()
End Sub
推荐阅读
- android - 导航架构组件 - 将参数数据传递给 startDestination
- php - Form.php 文件不通过输入的数据发送
- javascript - 为什么我的方法未定义?
- c# - 如何将 displaymenber 和 value menber 添加到列表框
- android - 删除 avd 文件
- azure - 通过 Azure 机器学习工作室将 Azure ML 实验部署为 Web 服务
- c# - 使用 Telegram 和 BotFramework 发送贴纸(使用 file_id,而不是 url)
- jquery - 与 angularjs 动态数据一起使用时 Jquery 数据表重新加载问题
- r - 基于组创建新列并使用基于其他组的总和填充这些列
- python - Python - 从excel列列表创建多个文件夹