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
Related
i put this code because i used combobox and they fill my two textbox,but when try to save its not saving the data that i put
this is the code
Sub loaddata()
Try
reload("SELECT * FROM NAME", STUDENT)
STUDENT.DataSource = dt
STUDENT.DisplayMember = "NAME"
STUDENT.ValueMember = "ID"
Catch ex As Exception
End Try
End Sub
Private Sub NAME_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NAME.SelectedIndexChanged
Try
Dim sql As String
Dim cmd As New OleDbCommand
Dim dt As New DataTable
Dim da As New OleDbDataAdapter
strcon.Open()
sql = "SELECT * FROM STUDENT where NAME LIKE '%" & NAME.Text & "%'"
cmd.Connection = strcon
cmd.CommandText = sql
da.SelectCommand = cmd
da.Fill(dt)
If dt.Rows.Count > 0 Then
GENDER.Text = dt.Rows(0).Item("GENDER").ToString
ADDRESS.Text = dt.Rows(0).Item(" ADDRESS").ToString
End If
Catch ex As Exception
Finally
strcon.Close()
End Try
End Sub
please show me how to put the save codes here,because i use only the BindingNavigator1 to save, but it does not save, sorry if my grammar is wrong because i'm not a fluent in english
I know we have a language barrier but we are both trying our best. I have provided a few examples of code to interact with a database.
It is a good idea to keep you database code separate from you user interface code. If you want to show a message box in you Try code, keep the Try in the user interface code. The error will bubble up from the database code to the calling code.
Using...End Using blocks take care of disposing of database objects. Parameters protect against Sql injection because parameter values are not considered executable code by the database. Note that for OleDb data sources the order that the parameters appear in the sql statement must match the order that they are added to the Parameters collection.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim dt = GetOriginalData()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "ID"
ComboBox1.DataSource = dt
End Sub
Private Function GetOriginalData() As DataTable
Dim dt As New DataTable
Using cn As New OleDbConnection("Your first connection string"),
cmd As New OleDbCommand("Select ID, Name From Table1;")
cn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
InsertData(CInt(ComboBox1.SelectedValue), ComboBox1.SelectedText, txtGender.Text, txtAddress.Text)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub InsertData(id As Integer, name As String, gender As String, address As String)
Using cn As New OleDbConnection("Your second connection string"),
cmd As New OleDbCommand("Insert Into Table2 (ID, Name, Gender, Address) Values (#ID, #Name, #Gender, #Address);", cn)
With cmd.Parameters
.Add("#ID", OleDbType.Integer).Value = id
.Add("#Name", OleDbType.VarChar).Value = name
.Add("#Gender", OleDbType.VarChar).Value = gender
.Add("#Address", OleDbType.VarChar).Value = address
End With
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
Loading data from SQL server into datagridview but Warning 1 Variable 'dtApplicantLists' is used before it has been assigned a value. A null reference exception could result in runtime. green underline at dtApplicantLists.Load(reader)
Any help, please...
Private Function GetList() As DataTable
Dim dtApplicantLists As DataTable
Dim connString As String = ConfigurationManager.ConnectionStrings("dbx").ConnectionString
Using conn As New SqlConnection(connString)
Using cmmd As New SqlCommand("SELECT FirstName, LastName, Gender, ChosenProg, Aggregate FROM dbo.Applicants", conn)
conn.Open()
Dim reader As SqlDataReader = cmmd.ExecuteReader()
dtApplicantLists.Load(reader)
End Using
End Using
Return dtApplicantLists
End Function
You need to call dtApplicantLists = New DataTable - currently it is null (or Nothing in VB).
Using ... End Using Method will guarantee you won't need to worry about warnings like this one you got, as obviously demonstrated in your Code.
Private Function GetList() As DataTable
Dim SqlStr As String =
("SELECT FirstName, LastName, Gender, ChosenProg, Aggregate FROM dbo.Applicants")
Using dtApplicantLists As DataTable = New DataTable
Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("dbx").ConnectionString),
Cmd As New SqlCommand(SqlStr, conn)
conn.Open()
Using Reader As SqlDataReader = Cmd.ExecuteReader
dtApplicantLists.Load(Reader)
End Using
End Using
Return dtApplicantLists
End Using
End Function
You can do it this way.
Imports System.Data.SqlClient
Public Class Form1
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim cmdBuilder As SqlCommandBuilder
Dim ds As New DataSet
Dim changes As DataSet
Dim sql As String
Dim i As Int32
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
connection = New SqlConnection(connetionString)
Sql = "select * from Product"
Try
connection.Open()
adapter = New SqlDataAdapter(Sql, connection)
adapter.Fill(ds)
connection.Close()
DataGridView1.Data Source= ds.Tables(0)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Try
cmdBuilder = New SqlCommandBuilder(adapter)
changes = ds.GetChanges()
If changes IsNot Nothing Then
adapter.Update(changes)
End If
MsgBox("Changes Done")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
See the link below for some other similar, but slightly different options.
http://vb.net-informations.com/dataadapter/dataadapter-datagridview-sqlserver.htm
I have the following code for a login winform. When I make the connection to the database and make a select statement I get no rows back. I'm getting the message "No data exists for the row/column."
But there are rows and columns in the database.
Can someone tell me what I do wrong?
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
Dim connectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("MySqlConnectionString").ConnectionString
Using con As New OleDbConnection(connectionString)
Dim intResult As Integer = 0
' MsgBox(connectionString)
Try
con.Open()
Using cmd As New OleDbCommand("SELECT Gebruikersnaam FROM Gebruikers WHERE Gebruikers.Gebruikersnaam = #Username", con)
cmd.Parameters.AddWithValue("#Username", UsernameTextBox.Text)
cmd.Parameters.AddWithValue("#Password", PasswordTextBox.Text)
Using dr As OleDbDataReader = cmd.ExecuteReader()
'intResult = CInt(cmd.ExecuteScalar)
'If intResult > 0 Then
MsgBox(dr.Item("Gebruikersnaam").ToString)
'End If
With dr
While .Read()
MsgBox(.HasRows)
'MsgBox(.Item("Gebruikersnaam"))
'TextBox1.Text = .Item("Gebruikersnaam") & vbCrLf
End While
End With
End Using
End Using
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
Me.Close()
End Using
End Sub
The problem was checking dr.Item() before ever calling dr.Read(). Aside from the that, make sure the username in UsernameTextBox actually exists in the database, fix those nasty plain-text passwords, and you'll be fine.
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
Dim connectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("MySqlConnectionString").ConnectionString
Try
Dim result As New StringBuilder()
Using con As New OleDbConnection(connectionString)
Using cmd As New OleDbCommand("SELECT Gebruikersnaam FROM Gebruikers WHERE Gebruikersnaam = #Username", con)
cmd.Parameters.AddWithValue("#Username", UsernameTextBox.Text)
cmd.Parameters.AddWithValue("#Password", PasswordTextBox.Text)
con.Open()
Using dr As OleDbDataReader = cmd.ExecuteReader()
While dr.Read()
'MsgBox(dr("Gebruikersnaam"))
result.AppendLine(dr("Gebruikersnaam"))
End While
End Using
End Using
End Using
TextBox1.Text = result.ToString()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
One final concern. I'm not sure which OLE provider you're using, but last time I checked most providers where it makes sense to use OLE want you to use ? placeholders instead of named parameters. So the SQL command would look like this:
SELECT Gebruikersnaam FROM Gebruikers WHERE Gebruikersnaam = ?
But if you're really using MySql, as the connection string name suggests, you really do so much better getting the real MySql ADO.Net library instead of OleDB: minor performance gain, better error messaging, etc.
The SelectCommand property has not been initialized before calling 'Fill' problem:
Private Sub DeleteButton_Click(sender As Object, e As EventArgs) Handles DeleteButton.Click
Dim tables As DataTableCollection
Dim source1 As New BindingSource
Dim row As New Integer
Try
ds = New DataSet
tables = (ds.Tables)
da = New OleDbDataAdapter
da.Fill(ds, "Booking")
Dim cmdstr As String = "delete * from [Booking] where ID = " & DataGridView1.SelectedRows(0).Cells(0).Value.ToString()
Dim cmd As New OleDbCommand(cmdstr, objCon)
da.SelectCommand = cmd
objCon.Open()
cmd.ExecuteNonQuery()
objCon.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Change
da.SelectCommand = cmd
With
da.DeleteCommand = cmd
Reguarding the Dim statements at the beginning of your code; you never use tables, source1 or row in your code so, there is no point in declaring them.
On to the Try You assign a New DataSet to ds. This is empty so assigned the Tables collection to tables makes no sense. This will be empty also.
Next you create a New DataAdapter. A new DataAdapter has no select command so it will be unable to .Fill anything.
Then you assign a Delete command to the SelectCommand property of a DataAdapter. This makes no sense.
Finally you execute you command. This should work if wasn't for the other code.
Keep you Database objects local so you can control their closing and disposing. Using...End Using takes care of this for you. The Using also acts as a Dim statement so it also declares you variables. You can include more than one variable with a single Using by separating them by a comma.
I guessed at the datatype of you ID field. Check your database.
Private Sub DeleteButton_Click(sender As Object, e As EventArgs) Handles DeleteButton.Click
Try
Using cn As New OleDbConnection("Your connection string"),
cmd As New OleDbCommand("delete * from [Booking] where ID = #ID", cn)
cmd.Parameters.Add("#ID", OleDbType.Integer).Value = DataGridView1.SelectedRows(0).Cells(0).Value
cn.Open()
cmd.ExecuteNonQuery()
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
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