这是我正在处理的代码,用于将图像插入数据库。我认为第一部分没有错。但是,某种程度上,此代码无法正常运行(没有图像插入数据库)。我不确定代码的注释部分是否与执行相关。我应该如何以更可行的方式开发它?该命令旨在与将键入的数据列表保存到数据库中一起执行。你能帮忙的话,我会很高兴。
Using con As SqlConnection = New SqlConnection("Data Source=LAPTOP-85ALBAVS\SQLEXPRESS;Initial Catalog=Portal;Integrated Security=True")
Using cmd As SqlCommand = New SqlCommand("INSERT INTO Photo (Img, Pid) VALUES (@Img, @Pid)", con)
Using ms As New MemoryStream
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat)
cmd.Parameters.Add("@Img", SqlDbType.Image).Value = ms.ToArray()
cmd.Parameters.Add("@Pid", SqlDbType.VarChar).Value = TextBox1.Text
End Using
End Using
End Using
'con.Open()
'If Command.ExecuteNonQuery() = 1 Then
' MessageBox.Show("Profile successfully registered!", "Message", MessageBoxButtons.OK)
'Else
' MessageBox.Show("Failed. Try again.", "Message", MessageBoxButtons.OK)
'End If
'con.Close()
End Sub
这是我用来从数据库检索图像并显示它的代码。此代码有故障。如果未找到与特定图片相关的图片Pid
,则会弹出错误消息'There is no row at position 0.'
(表示未上传图片)。但这并不会对整个程序的执行产生太大影响,只要将图像与键入的数据一起成功上传就可以了。
Dim command As New SqlCommand("Select * From Photo Where Pid = @Pid", con)
command.Parameters.Add("@Pid", SqlDbType.VarChar).Value = TextBox1.Text
Dim table As New DataTable()
Dim adapter As New SqlDataAdapter(command)
adapter.Fill(table)
Dim img() As Byte
img = table.Rows(0)(0)
Dim ms As New MemoryStream(img)
pictureBox1.Image = Image.FromStream(ms)
我解决了这个问题,这是它的代码。请随时检查它,希望它对以后的人有所帮助:)
Using con As SqlConnection = New SqlConnection("Data Source=LAPTOP-85ALBAVS\SQLEXPRESS;Initial Catalog=Portal;Integrated Security=True")
Using cmd As SqlCommand = New SqlCommand("INSERT INTO Photo (Img, Pid) VALUES (@Img, @Pid)", con)
Using ms As New MemoryStream
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat)
cmd.Parameters.Add("@Img", SqlDbType.Image).Value = ms.ToArray()
cmd.Parameters.Add("@Pid", SqlDbType.VarChar).Value = TextBox1.Text
con.Open()
cmd.ExecuteNonQuery()
MessageBox.Show("Profile has been successfully registered!", "Thank you", MessageBoxButtons.OK)
End Using
End Using
End Using
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句