Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何在不影响将照片上载到数据库的情况下正确执行rd.HasRow?_Sql_Vb.net_Sqldatareader - Fatal编程技术网

Sql 如何在不影响将照片上载到数据库的情况下正确执行rd.HasRow?

Sql 如何在不影响将照片上载到数据库的情况下正确执行rd.HasRow?,sql,vb.net,sqldatareader,Sql,Vb.net,Sqldatareader,在将键入的数据保存到数据库之前,我尝试使用rd.HasRow方法验证键入的数据是否重复 如果重复,则会弹出错误消息框,而不是保存数据 我应该如何执行这个命令,以及我用来上传照片到数据库的代码?如果我对这部分代码进行注释,输入的未复制数据可以保存到数据库中,但照片不会随它一起上载 'i=cmd.ExecuteNonQuery '如果i>=1,则 'MessageBox.ShowProfile已成功注册!,Message,MessageBoxButtons.OK,MessageBoxIcon.Inf

在将键入的数据保存到数据库之前,我尝试使用rd.HasRow方法验证键入的数据是否重复

如果重复,则会弹出错误消息框,而不是保存数据

我应该如何执行这个命令,以及我用来上传照片到数据库的代码?如果我对这部分代码进行注释,输入的未复制数据可以保存到数据库中,但照片不会随它一起上载

'i=cmd.ExecuteNonQuery '如果i>=1,则 'MessageBox.ShowProfile已成功注册!,Message,MessageBoxButtons.OK,MessageBoxIcon.Information ”“否则呢 'MessageBox.bathror。请稍后再试,消息,MessageBoxButtons.OK,MessageBoxIcon.Information "完" 但如果我不这样做,则用户键入的数据将不会保存,并且将针对I=cmd.ExecuteNonQuery弹出此错误消息:

System.InvalidOperationException:'已经有一个与此命令关联的打开的DataReader,必须先关闭它。'

这是全部代码

私有子按钮2\u单击发件人作为对象,e作为事件args处理按钮2。单击 Dim con作为新的SqlConnection Dim cmd作为新的SqlCommand 模糊罗尔诺字符串 将名称设置为字符串 朦胧的性别 作为字符串的Dim地址 Dim phoneno作为整数 Dim datereg作为字符串 像弦一样模糊 像绳子一样模糊的路线 像弦一样模糊 作为整数的Dim i 作为整数的Dim j rollno=TextBox1.Text name=TextBox2.Text 性别=组合框4.Text 地址=TextBox3.Text phoneno=TextBox4.Text datereg=dateTimePicker1.Value faculty=comboBox1.Text course=comboBox2.Text 学期=组合框3.Text con.ConnectionString=Data Source=LAPTOP-85ALBAVS\SQLEXPRESS;初始目录=门户;集成安全性=真 cmd.Connection=con 未结 '要验证用户键入的数据是否重复,如果是,将弹出错误消息。如果否,继续并将数据保存到数据库中 Dim rd作为SqlDataReader cmd.CommandText=从配置文件中选择*,其中RollNo='&TextBox1.Text&'和Name='&TextBox2.Text&' rd=cmd.ExecuteReader 如果rd.HasRows那么 MessageBox.ShowUser已注册!请重试,错误,MessageBoxButtons.OK 其他的 cmd.CommandText=插入配置文件值“&rollno&'、”&name&'、“&gender&'、“&address&'、“&phoneno&'、”&datereg&'、“&faculty&'、“&course&'、”和sement&' 如果结束 'i=cmd.ExecuteNonQuery '如果i>=1,则 'MessageBox.ShowProfile已成功注册!,Message,MessageBoxButtons.OK,MessageBoxIcon.Information ”“否则呢 'MessageBox.bathror。请稍后再试,消息,MessageBoxButtons.OK,MessageBoxIcon.Information "完" 结案 未结 '将上载的照片保存到表格照片 Dim命令作为新的SqlCommandInsert插入照片Img,Pid值@Img,@Pid,con command.Connection=con 将ms变暗为新内存流 pictureBox1.Image.Savems,pictureBox1.Image.RawFormat 命令参数。Add@Img,SqlDbType.Image.Value=ms.ToArray 命令参数。Add@Pid,SqlDbType.VarChar.Value=TextBox1.Text j=cmd.ExecuteNonQuery 如果j>=1,则 MessageBox.ShowProfile已成功注册!,Message,MessageBoxButtons.OK,MessageBoxIcon.Information 其他的 MessageBox.ShowError。请稍后再试,消息,MessageBoxButtons.OK,MessageBoxIcon.Information 如果结束 端接头
评论和解释一致

Private Sub OPCode()
        Dim i As Integer
        Dim j As Integer
        Dim rollno = TextBox1.Text
        Dim name = TextBox2.Text
        Dim gender = ComboBox4.Text
        Dim address = TextBox3.Text
        Dim phoneno = CInt(TextBox4.Text) 'Unless your phone numbers are very different
        'than the phone numbers here, the likelyhood of a user entering just numbers is
        'nil. Change this to a string and a VarChar in the database
        Dim datereg = dateTimePicker1.Value
        Dim faculty = comboBox1.Text
        Dim course = ComboBox2.Text
        Dim semester = ComboBox3.Text
        'The Using block ensures that your connection is closed and disposed
        'Pass your connection string to the constructor of the connection
        Using con As New SqlConnection("Data Source=LAPTOP-85ALBAVS\SQLEXPRESS;Initial Catalog=Portal;Integrated Security=True")
            'Pass the Sql command text and connection to the Constructor of the command.
            'NEVER, NEVER, NEVER allow user input to be passed directly to a database. Always use parameters.
            Dim cmd As New SqlCommand("SELECT * FROM Profile WHERE RollNo= @RollNo and [Name]= @Name;", con)
            cmd.Parameters.Add("@RollNo", SqlDbType.VarChar).Value = rollno
            cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = name
            con.Open()
            Using rd As SqlDataReader = cmd.ExecuteReader()
                'To validate whether duplication of typed in data by user occurs or not, if yes, error msg pop-up. If no, proceed and save the data into database
                If rd.HasRows Then
                    MessageBox.Show("User already registered! Please try again.", "Error", MessageBoxButtons.OK)
                    'You don't want to go any further if the user is registered.
                    Exit Sub
                End If
            End Using
            'Just use another new command variable to avoid confusion
            'I think it is much better practice to list the fields.
            Dim cmd2 As New SqlCommand("INSERT INTO Profile VALUES (@RollNo ,@Name,@Gender, @Address, @PhoneNo , @DateReg , @Faculty , @Course , @Semester);", con)
            cmd2.Parameters.Add() 'etc.
            i = cmd2.ExecuteNonQuery()
            If i >= 1 Then
                MessageBox.Show("Profile successfully registered!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Else
                MessageBox.Show("Error. Please try again later.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Sub
            End If
            'To save the uploaded photo to table Photo
            Dim command3 As New SqlCommand("Insert into Photo (Img, Pid) Values (@Img, @Pid)", con)
            command3.Connection = con
            Dim ms As New MemoryStream
            pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat)
            command3.Parameters.Add("@Img", SqlDbType.Image).Value = ms.ToArray()
            command3.Parameters.Add("@Pid", SqlDbType.VarChar).Value = TextBox1.Text

            j = command3.ExecuteNonQuery()
        End Using
        If j >= 1 Then
                MessageBox.Show("Profile successfully registered!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Else
                MessageBox.Show("Error. Please try again later.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
    End Sub

代码看起来有点凌乱,根据我的经验,调试凌乱的代码可能很困难。我们可以做一些事情来纠正这一点,我现在将尝试与你们一起做

首先,为控件指定有意义的名称。通过选择控件并更改Name属性,可以通过窗体上的设计实现这一点。当通过代码引用它们时,这将极大地帮助您。在这种情况下,它还将帮助您消除对变量的需要

考虑实施:

有时,代码需要非托管资源,例如文件句柄、COM包装器或SQL连接。Using块保证在代码使用完一个或多个这样的资源后可以对它们进行处理。这使它们可供其他代码使用

这将帮助您管理您的声明和资源,同时还可以更清晰地了解您的代码

我也会考虑使用块将每个命令都分解成自己的命令,以使代码更加清晰。

在将数据插入数据库时,应考虑避免使用./P> 最后是代码,让我们依次查看每个Using块

首先,我将在Using块中启动SqlConnection,然后我们可以对每个命令使用该连接:< /p> 使用con作为新的SqlConnectionData Source=LAPTOP-85ALBAVS\SQLEXPRESS;初始目录=门户;集成安全性=真 未结 '在此处添加其余代码 终端使用 检查记录是否存在:

这里,考虑声明一个布尔变量,我们使用它来确定记录是否存在

Dim recordExists As Boolean = False
Using cmd As New SqlCommand("SELECT * FROM Profile WHERE RollNo = @RollNo AND Name = @Name", con)
    cmd.Parameters.Add("@RollNo", SqlDbType.[Type]).Value = txtRollNo.Text
    cmd.Parameters.Add("@Name", SqlDbType.[Type]).Value = txtName.Text

    Using reader As SqlDataReader = cmd.ExecuteReader()
        recordExists = reader.HasRows
    End Using
End Using
如果记录存在,则显示提示;如果记录不存在,则插入数据库:

插入图像:

请注意,我使用了SqlDbType.[Type],其中我不确定数据库中的数据类型。您需要将其替换为为为每列指定的数据类型

总之,您的代码如下所示:

Using con As New SqlConnection("Data Source=LAPTOP-85ALBAVS\SQLEXPRESS;Initial Catalog=Portal;Integrated Security=True")

    con.Open()

    Dim recordExists As Boolean = False
    Using cmd As New SqlCommand("SELECT * FROM Profile WHERE RollNo = @RollNo AND Name = @Name", con)
        cmd.Parameters.Add("@RollNo", SqlDbType.VarChar).Value = txtRollNo.Text
        cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = txtName.Text

        Using reader As SqlDataReader = cmd.ExecuteReader()
            recordExists = reader.HasRows
        End Using
    End Using

    If recordExists Then
        MessageBox.Show("User already registered! Please try again.", "Error", MessageBoxButtons.OK)
    Else
        Using cmd As New SqlCommand("INSERT INTO Profile VALUES (@RollNo, @Name, @Gender, @Address, @PhoneNo, @DateReg, @Faculty, @Course, @Semester)", con)

            cmd.Parameters.Add("@RollNo", SqlDbType.[Type]).Value = txtRollNo.Text
            cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = txtName.Text
            cmd.Parameters.Add("@Gender", SqlDbType.VarChar).Value = cboGender.Text
            cmd.Parameters.Add("@Address", SqlDbType.VarChar).Value = txtAddress.Text
            cmd.Parameters.Add("@PhoneNo", SqlDbType.VarChar).Value = txtPhoneNo.Text
            cmd.Parameters.Add("@DateReg", SqlDbType.VarChar).Value = dtpDateReg.Value
            cmd.Parameters.Add("@Faculty", SqlDbType.VarChar).Value = cboFaculty.Text
            cmd.Parameters.Add("@Course", SqlDbType.VarChar).Value = cboCourse.Text
            cmd.Parameters.Add("@Semester", SqlDbType.VarChar).Value = cboSemster.Text

            con.Open()

            If cmd.ExecuteNonQuery() > 0 Then
                MessageBox.Show("Profile successfully registered!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Else
                MessageBox.Show("Error. Please try again later.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        End Using
    End If

    Using cmd As New SqlCommand("INSERT INTO Photo (Img, Pid) VALUES (@Img, @Pid)", con)

        Using ms As New MemoryStream()
            pbxImage.Image.Save(ms, pbxImage.Image.RawFormat)

            cmd.Parameters.Add("@Img", SqlDbType.Image).Value = ms.ToArray()
            cmd.Parameters.Add("@Pid", SqlDbType.VarChar).Value = txtName.Text
        End Using

        con.Open()

        cmd.ExecuteNonQuery()
    End Using

End Using

这段代码未经测试,我没有环境,但它应该给您一些可以使用的东西。

cm2.Parameters.AddError:重载解析失败,因为没有可访问的“Add”接受此数量的参数。@no0b3-该行有一条注释“ect”,这意味着您应该提供其余的参数。看下面几行的例子。
Using cmd As New SqlCommand("INSERT INTO Photo (Img, Pid) VALUES (@Img, @Pid)", con)

    Using ms As New MemoryStream()
        pbxImage.Image.Save(ms, pbxImage.Image.RawFormat)

        cmd.Parameters.Add("@Img", SqlDbType.Image).Value = ms.ToArray()
        cmd.Parameters.Add("@Pid", SqlDbType.VarChar).Value = txtName.Text
    End Using

    cmd.ExecuteNonQuery()
End Using
Using con As New SqlConnection("Data Source=LAPTOP-85ALBAVS\SQLEXPRESS;Initial Catalog=Portal;Integrated Security=True")

    con.Open()

    Dim recordExists As Boolean = False
    Using cmd As New SqlCommand("SELECT * FROM Profile WHERE RollNo = @RollNo AND Name = @Name", con)
        cmd.Parameters.Add("@RollNo", SqlDbType.VarChar).Value = txtRollNo.Text
        cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = txtName.Text

        Using reader As SqlDataReader = cmd.ExecuteReader()
            recordExists = reader.HasRows
        End Using
    End Using

    If recordExists Then
        MessageBox.Show("User already registered! Please try again.", "Error", MessageBoxButtons.OK)
    Else
        Using cmd As New SqlCommand("INSERT INTO Profile VALUES (@RollNo, @Name, @Gender, @Address, @PhoneNo, @DateReg, @Faculty, @Course, @Semester)", con)

            cmd.Parameters.Add("@RollNo", SqlDbType.[Type]).Value = txtRollNo.Text
            cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = txtName.Text
            cmd.Parameters.Add("@Gender", SqlDbType.VarChar).Value = cboGender.Text
            cmd.Parameters.Add("@Address", SqlDbType.VarChar).Value = txtAddress.Text
            cmd.Parameters.Add("@PhoneNo", SqlDbType.VarChar).Value = txtPhoneNo.Text
            cmd.Parameters.Add("@DateReg", SqlDbType.VarChar).Value = dtpDateReg.Value
            cmd.Parameters.Add("@Faculty", SqlDbType.VarChar).Value = cboFaculty.Text
            cmd.Parameters.Add("@Course", SqlDbType.VarChar).Value = cboCourse.Text
            cmd.Parameters.Add("@Semester", SqlDbType.VarChar).Value = cboSemster.Text

            con.Open()

            If cmd.ExecuteNonQuery() > 0 Then
                MessageBox.Show("Profile successfully registered!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Else
                MessageBox.Show("Error. Please try again later.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        End Using
    End If

    Using cmd As New SqlCommand("INSERT INTO Photo (Img, Pid) VALUES (@Img, @Pid)", con)

        Using ms As New MemoryStream()
            pbxImage.Image.Save(ms, pbxImage.Image.RawFormat)

            cmd.Parameters.Add("@Img", SqlDbType.Image).Value = ms.ToArray()
            cmd.Parameters.Add("@Pid", SqlDbType.VarChar).Value = txtName.Text
        End Using

        con.Open()

        cmd.ExecuteNonQuery()
    End Using

End Using