i want save a picture into daatabase - vb.net

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim a As New OpenFileDialog
con.ConnectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\USERS\USER\DOWNLOADS\SDP(BACKUP1)\SDP(BACKUP)\SDP.MDF;Integrated Security=True"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO Announcement ([name],[picture]) VALUES('" & nameTB.Text & "',#a2)"
cmd.Parameters.Add(New SqlClient.SqlParameter("#a2", SqlDbType.Image)).Value = IO.File.ReadAllBytes(PictureBox2.BackgroundImage)
cmd.ExecuteNonQuery()
MsgBox("Event Announcement submitted!")
con.Close()
Catch ex As Exception
MsgBox("Operation Failed! Please Check Again!")
End Try
End Sub
this is what i had try....i can choose a image but i cant save it(which mean complete save a picture into database) all that thing in google teach me save picture in sql server or access.. i had try it...but the very last thing i dunt understand is how can i parameter #a2 with picturebox?
it give error for IO.File.ReadAllBytes(PictureBox2.BackgroundImage)

As commented, File.ReadAllBytes wants a file, not an image. So you need to use a MemoryStream instead:
Using ms As New MemoryStream
PictureBox2.BackgroundImage.Save(ms, ImageFormat.Png)
cmd.Parameters.AddWithValue("#a2", ms.ToArray)
End Using

Related

Fatal error encountered during command execution.'

I want to save the rows of datagridview into the database. I am using editbtn click button, when I press the button it gives me the following error: "Fatal error encountered during command execution." Here is the code which I am using
Private Sub Supplier_Load(sender As Object, e As EventArgs) Handles MyBase.Load
conn.ConnectionString = "Server=127.0.0.1;Database=pembelian;Uid=root;Pwd=;"
If conn.State = ConnectionState.Open Then
conn.Close()
End If
conn.Open()
disp_data()
End Sub
Public Sub disp_data()
cmd = conn.CreateCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = "select * from supplier"
cmd.ExecuteNonQuery()
Dim dt As New DataTable()
Dim da As New MySqlDataAdapter(cmd)
da.Fill(dt)
DataGridView1.DataSource = dt
End Sub
Private Sub edit_btn_Click(sender As Object, e As EventArgs) Handles edit_btn.Click
Dim query As String = "updates supplier set nama=#nama, alamat=#alamat where npwp=#npwp"
cmd = New MySqlCommand(query, conn)
cmd.Parameters.AddWithValue("#nama", nama.Text)
cmd.Parameters.AddWithValue("#alamat", alamat.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("Data berhasil di update")
disp_data()
End Sub
First of all, it's not good to re-use the same connection object throughout your application. There is a feature in ADO.Net called connection pooling, where the MySqlConnection object you use in your code is actually a simple wrapper for the real underlying connection. These real connections are much heavier and more expensive to manage. They handle the real work of authentication, getting network socket resources, negotiating with the server, etc.
When you try to re-use the same connection object, you are optimizing the small thing (MySqlConnection) at the expense of the big thing (the real underlying connections). Don't do that.
Instead, you really are much better off creating a new connection for most queries, and then returning it to the pool as quickly as possible. This is normally handled with a Using block.
That out of the way I can look at the actual question. I noticed the #npwp parameter is not defined in the last method. Guessing at the name of the appropriate field, you want something more like this:
Private Sub edit_btn_Click(sender As Object, e As EventArgs) Handles edit_btn.Click
Dim query As String = "updates supplier set nama=#nama, alamat=#alamat where npwp=#npwp"
Using conn As New MySqlConnection("Server=127.0.0.1;Database=pembelian;Uid=root;Pwd=;")
Using cmd As New MySqlCommand(query, conn)
cmd.Parameters.AddWithValue("#nama", nama.Text)
cmd.Parameters.AddWithValue("#alamat", alamat.Text)
cmd.Parameters.AddWithValue("#npwp", npwp.Text)
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
MessageBox.Show("Data berhasil di update")
disp_data()
End Sub
Public Sub disp_data()
Dim dt As New DataTable()
Dim query As String = "select * from supplier"
Using conn As New MySqlConnection("Server=127.0.0.1;Database=pembelian;Uid=root;Pwd=;")
Using cmd As New MySqlCommand(query, conn)
Using da As New MySqlDataAdapater(cmd)
da.Fill(dt)
End Using
End Using
End Using
DataGridView1.DataSource = dt
End Sub

ComboBox connection with database

I am trying to link the combobox with my database column "name", for this purpose i am watching a tutorial from youtube. Everything is going smooth but now I am having problem with connecting it with a combobox. I am new to VB.Net, so please guide me.
Here is my code:
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con = New SqlConnection
con.ConnectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\zeeshan\documents\visual studio 2013\Projects\Tutorials\Tutorials\Register.mdf"
Dim READER As SqlDataReader
Try
con.Open()
Dim Query As String
Query = "select * from dbo.edata"
cmd = New SqlCommand(Query, con)
READER = cmd.ExecuteReader
While READER.Read
Dim sName = READER.GetString("name")
ComboBox1.Items.Add(sName)
End While
con.Close()
Catch ex As SqlException
MessageBox.Show(ex.Message)
Finally
con.Dispose()
End Try
End Sub
I have attached the error pic as well. This code is working fine in video tutorial but I m having problem using it.
datatable dt= cmd.ExecuteReader
if(dt.rows.count>0)
{
foreach(Datarow dr in dt.rows)
{
ComboBox1.Items.Add(dt.Rows[0]["Name"].ToString());
}
}
Use index column
While READER.Read
Dim sName = READER.GetString(1)
ComboBox1.Items.Add(sName)
End While

How to connect to db via vb.net?

I have the following code, the msgBox that says "DB changed" never shows up, and I get messages like follows in the immediate window.
But finally, the form loads, and I can't know whether my DB was created or not!
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim strConn As String = "Data Source=localhost;Initial Catalog=master;Integrated Security=True"
Dim conn As New SqlConnection(strConn)
conn.Open()
Try
conn.ChangeDatabase("productsDB")
MsgBox("DB changed")
Catch ex As Exception
Try
Dim command1 As New SqlCommand("CREATE DATABASE productsDB", conn)
command1.ExecuteNonQuery()
command1.Connection.ChangeDatabase("productsDB")
Dim command2 As New SqlCommand("CREATE TABLE products ([id][int],[name][char](30),[quantity][int],[dealer_price][int],[unit_price][int])", conn)
command2.ExecuteNonQuery()
Catch ex2 As Exception
MsgBox(ex2.Message)
End Try
End Try
End Sub
It might be helpful if you instantiate the connection, as well as open it, inside the try block to see the exception you are throwing.
Dim conn as SqlConnection
Try
conn = new SqlConnection(strConn)
con.Open()
...
Catch ex As Exception
MsgBox.Show(ex.Message)
End Try

returning select value using Visual Basic 2010 oleDB

I'm trying to read a excel cell with visual basic 2010 ( I'm really new to this) and I think I finally did it BUT I have no clue how to return the result.
It should end up in the clipboard or msgBox from there I'll find my way :D
I searched for two hours now but didnt find the solution... please help me
Thanks
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
cn.ConnectionString = "provider=microsoft.jet.oledb.4.0;data source=C:\Users\marcelf\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplication1\bin\Debug\DB.xls;extended properties=excel 8.0;"
cn.Open()
With cm
.Connection = cn
.CommandText = "SELECT * FROM [ccs$C1:B20] WHERE 'id' = 'German'"
.ExecuteNonQuery()
End With
cn.Close()
MsgBox(????)
End Sub
EDIT: her is the updated code. I get "Could not find installable ISAM
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
Dim con As New OleDbConnection
Try
Using con
'added HDR=No to the extended properties of the connection string
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\Users\marcelf\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplicat'ion1\bin\Debug\DB.xls;extended properties=excel 12.0;HDR=Yes"
con.Open()
Using cmd = New OleDbCommand
cmd.Connection = con
cmd.CommandText = "SELECT * FROM [ccs$C1:C20] WHERE 'id' = 'German'"
Using oRDR As OleDbDataReader = cmd.ExecuteReader
While (oRDR.Read)
MsgBox(oRDR.GetValue(0)) 'gets the first returned column
End While
End Using
con.Close()
End Using
End Using
Catch ex As Exception
Throw New Exception(ex.Message)
Finally
con.Close()
End Try
End Sub
EDIT: That's what worked for me:
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
Dim con As New OleDbConnection
Try
Using con
'added HDR=No to the extended properties of the connection string
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\marcelf\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplication1\bin\Debug\DB.xls;Mode=3;User ID=Admin;Password=;Extended Properties=Excel 8.0"
con.Open()
Using cmd = New OleDbCommand
cmd.Connection = con
cmd.CommandText = "SELECT Service FROM [ccs$] WHERE id='" & ComboBox1.SelectedItem & "'"
Using oRDR As OleDbDataReader = cmd.ExecuteReader
While (oRDR.Read)
MsgBox(oRDR.GetValue(0)) 'gets the first returned column
End While
End Using
con.Close()
End Using
End Using
Catch ex As Exception
Throw New Exception(ex.Message)
Finally
con.Close()
End Try
End Sub
Welcome to SO. In the future you should show us all of your code. Since you tagged OleDB and vb.net, the following implements what you are trying to accomplish. I included the Form Class so the Imports statements could be shown, but you can just copy and paste the click event code after insuring you Class includes the Imports. Note, I have not tested this code but it should work. Let me know if you need clarification or additional help.
Imports System.Data.OleDb
Public Class Form1
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
Dim con As New OleDbConnection
Try
Using con
'added HDR=No to the extended properties of the connection string
' **EDIT**
con.ConnectionString = "Provider=Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\marcelf\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplicat'ion1\bin\Debug\DB.xls;Mode=3;User ID=Admin;Password=;Extended Properties=Excel 8.0"
con.Open()
Using cmd = New OleDbCommand
cmd.Connection = con
cmd.CommandText = "SELECT * FROM [ccs$C1:B20] WHERE 'id' = 'German'"
Using oRDR As OleDbDataReader = cmd.ExecuteReader
While (oRDR.Read)
MsgBox(oRDR.GetValue(0)) 'gets the first returned column
End While
End Using
con.Close()
End Using
End Using
Catch ex As Exception
Throw New Exception(ex.Message)
Finally
con.Close()
End Try
End Sub
End Class

Reading OleDb records into TextBox using ComboBox VB.NET

I'm new to programming. What i'm trying to accomplish is to fill in 9 textboxes in VB.NET, reading access table TblKlanten, using a combobox (CbbNaamfirma). I cannot get this to work for the life of me; i've been searching for 6 hours for this simple thing. Can any of you help me out? I've read numerous threads on SO.com like this and they all just won't work for me.
Code i have now:
Private Sub CbbNaamfirma_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles CbbNaamfirma.SelectedIndexChanged
Dim Connection As New OleDb.OleDbConnection
Connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & Application.StartupPath & "\Database.accdb.'"
Try
Connection.Open()
Dim query As String
query = "SELECT Adres FROM TblKlanten WHERE [Naam firma] = ' " & CbbNaamfirma.Text & " ' "
Dim cmd As New OleDbCommand(query, Connection)
Dim Reader As OleDbDataReader = cmd.ExecuteReader
Reader = cmd.ExecuteReader
While Reader.Read
TxtAdresprev.Text = Reader.GetString("Adres")
End While
Connection.Close()
Catch ex As OleDbException
MessageBox.Show(ex.Message)
Finally
Connection.Dispose()
End Try
End Sub
Thank you in advance. Hope that code block turned out alright?
The first thing to change is the reading from the database using a parameterized query. Notice that your code cannot find anything because you add a space before and after the value of the combobox.
Then you need to start employing the using statement around the disposable objects to ensure a proper closing and disposing
Finally the GetString method from the OleDbDataReader wants a numeric index inside the returned list of fields, not the name of the field
Private Sub CbbNaamfirma_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles CbbNaamfirma.SelectedIndexChanged
Dim cnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & _
Application.StartupPath & "\Database.accdb"
Dim query = "SELECT Adres FROM TblKlanten WHERE [Naam firma] = ?"
Using Connection = New OleDb.OleDbConnection(cnString)
Using cmd = New OleDbCommand(query, Connection)
Try
Connection.Open()
cmd.Parameters.AddWithValue("#p1", CbbNaamfirma.Text)
Using Reader = cmd.ExecuteReader
While Reader.Read
Dim posAdres = Reader.GetOrdinal("Adres")
TxtAdresprev.Text = Reader.GetString(posAdres)
.... other text boxes for other fields here.....
End While
End Using
Catch ex As OleDbException
MessageBox.Show(ex.Message)
End Try
End Using
End Using
End Sub
Also your connection string seems to be wrong. No need of quotation and that stray point after the fielname is wrong