我正在为我们的论文制作学生管理系统。输入用户名和密码后,单击登录按钮时,此错误显示在da.Fill(dt)
中:
InvalidOperationException未处理
Fill
:SelectCommand.connection
属性尚未初始化。
这是我在登录按钮中的代码
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
cs = "Data Source=.\SQLEXPRESS;Initial Catalog=demo;Integrated Security=True"
con = New SqlConnection(cs)
Dim username As String = TextBox1.Text
Dim password As String = TextBox2.Text
cmd = New SqlCommand("select username,password from login where
username='" + TextBox1.Text + "'and password'" + TextBox2.Text + "' ")
da = New SqlDataAdapter(cmd)
dt = New DataTable()
da.Fill(dt)
If (dt.Rows.Count > 0) Then
name = TextBox1.Text
MessageBox.Show("Login Successful", "success!",
MessageBoxButtons.OK, MessageBoxIcon.Information)
content.Show()
Else
MsgBox("Invalid Login Information!", MessageBoxButtons.OK,
MessageBoxIcon.Error)
End If
End Sub
End Class
当我单击登录按钮时,我应该进入主页。
这是登录名:
这是家:
答案 0 :(得分:0)
您必须指定要在命令中使用哪个连接。
cmd = New SqlCommand("select username,password from login where
username='" + TextBox1.Text + "'and password'" + TextBox2.Text + "' ", con)
请注意,您正在串联字符串以构建SQL查询。这是非常不安全的。这导致SQL注入!请在字符串变量中至少使用双引号,并检查变量int。但我强烈建议您使用参数化变量(请参见sp_executeSql)。
cmd = New SqlCommand("select username,password from login where
username='" + TextBox1.Text.replace("'", "''") + "'and password'" + TextBox2.Text.replace("'", "''") + "' ", con)
答案 1 :(得分:0)
在线发表评论和解释。
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim cs = "Data Source=.\SQLEXPRESS;Initial Catalog=demo;Integrated Security=True"
Dim Exists As Boolean
'The Using block ensures that your database objects are closed and disposed
'even if there is an error.
Using con = New SqlConnection(cs)
'All you need to know is if the record exists. You do not need to return
'the values you just entered.
'Pass the connection to the constructor of the command
Using cmd = New SqlCommand("If Exists (Select username, password From login Where
username=@User and password = @Password;", con)
'Use parameters. It not only helps protect your database against SQL Injection but
'simplifies your SQL statement
cmd.Parameters.Add("@User", SqlDbType.VarChar).Value = TextBox1.Text
cmd.Parameters.Add("@Password", SqlDbType.VarChar).Value = TextBox2.Text
'You do not need a data adapter or data table for this
'Use execute scalar when you are returning a single value
con.Open()
Exists = CBool(cmd.ExecuteScalar)
End Using
End Using
If Exists Then
Name = TextBox1.Text
MessageBox.Show("Login Successful", "success!", MessageBoxButtons.OK, MessageBoxIcon.Information)
content.Show()
Else
MessageBox.Show("Invalid Login Information!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End Sub
编辑
永远不要将密码存储为纯文本。