SqlDataAdapter # Fill: свойство `SelectCommand.connection` не было инициализировано - PullRequest
0 голосов
/ 18 января 2019

Я делаю систему управления студентами для нашей диссертации. Когда я нажимаю кнопку входа в систему после ввода имени пользователя и пароля, эта ошибка отображается в da.Fill(dt):

Исключение InvalidOperationException было обработано

Fill: SelectCommand.connection свойство не было инициализировано.

Error screenshot

Вот мой код в кнопке входа в систему

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

Когда я нажимаю кнопку входа, я должен попасть на домашнюю страницу.

Это логин:

Login screenshot

а это дом:

Home page

Ответы [ 2 ]

0 голосов
/ 19 января 2019

Комментарии и пояснения в строке.

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

EDIT

Никогда не храните пароли в виде простого текста.

0 голосов
/ 18 января 2019

Вы должны указать, какое соединение использовать в вашей команде.

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)
...