Recently i build a pos but the datagridview doesnt refresh i tried different methods but its not worikng
Dim Query As String
Query = "insert into bazaartikli123.artikli(id,barkod,naziv,kupovna,prodazna,opis) values ('" & TextBoxBarkod.Text & "','" & TextBoxNaziv.Text & "','" & TextBoxKupovna.Text & "','" & TextBoxProdazna.Text & "','" & TextBoxOpis.Text & "')"
COMMAND = New MySqlCommand(Query, konecija)
READER = COMMAND.ExecuteReader
Dim dataadapter As New SqlDataAdapter(sql, konekcija)
Dim ds As New DataSet()
MessageBox.Show("Артиклот е успешно внесен !")
TextBoxBarkod.Text = ""
TextBoxKupovna.Text = ""
TextBoxNaziv.Text = ""
TextBoxOpis.Text = ""
TextBoxProdazna.Text = ""
dataadapter.Fill(ds)
konecija.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Artikli"
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
konecija.Dispose()
End Try
Bazadataset ,ArtikliBindingSource , ArtikliTableAdapter
Related
I'm getting this error when I click the update button in my form:
" An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Incorrect syntax near 'intGenderID'."
The update does not work.
Could anyone point me in the right direction? Thanks in advance!
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim strSelect As String = ""
Dim strFirstName As String = ""
Dim strLastName As String = ""
Dim strAddress As String = ""
Dim strCity As String = ""
Dim strState As String = ""
Dim strZip As String = ""
Dim strPhoneNumber As String = ""
Dim strEmail As String = ""
Dim intRowsAffected As Integer
Dim cmdUpdate As OleDb.OleDbCommand
If Validation() = True Then
' open database
If OpenDatabaseConnectionSQLServer() = False Then
' No, warn the user ...
MessageBox.Show(Me, "Database connection error." & vbNewLine &
"The application will now close.",
Me.Text + " Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End If
If Validation() = True Then
strFirstName = txtFirstName.Text
strLastName = txtLastName.Text
strAddress = txtAddress.Text
strCity = txtCity.Text
strState = txtState.Text
strZip = txtZip.Text
strPhoneNumber = txtPhoneNumber.Text
strEmail = txtEmail.Text
strSelect = "Update TGolfers Set strFirstName = '" & strFirstName & "', " & "strLastName = '" & strLastName &
"', " & "strAddress = '" & strAddress & "', " & "strCity = '" & strCity & "', " &
"strState = '" & strState & "', " & "strZip = '" & strZip & "', " &
"strPhoneNumber = '" & strPhoneNumber & "', " & "strEmail = '" & strEmail & "', " &
"intShirtSizeID = '" & cboShirtSizes.SelectedValue.ToString & "' " &
"intGenderID = '" & cboGenders.SelectedValue.ToString & "' " &
"Where intGolferID = " & cboGolfers.SelectedValue.ToString
MessageBox.Show(strSelect)
cmdUpdate = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
intRowsAffected = cmdUpdate.ExecuteNonQuery()
If intRowsAffected = 1 Then
MessageBox.Show("Update successful")
Else
MessageBox.Show("Update failed")
End If
CloseDatabaseConnection()
frmManageGolfers_Load(sender, e)
End If
End If
End Sub
Syntax error means that the SQL isn't the right syntax. Its quite strict.
Near 'intGenderID' means the syntax error is just before this. In your case, you've missed a comma.
I will proceed as if this MySql. Keep your database objects local. You need to keep track that they are closed and disposed. `Using...End Using blocks take care of this even if there is an error.
Always use parameters. Not only does it make writing the sql statement much easier it will save your database from sql injection.
Additional comments in-line.
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim intRowsAffected As Integer
Dim strSelect As String = "Update TGolfers Set strFirstName = #FirstName, strLastName = #LastName, strAddress = #Address, strCity = #City, strState = #State, strZip = #Zip, strPhoneNumber = #Phone, strEmail = #EMail, intShirtSizeID = #ShirtSize, intGenderID = #Gender Where intGolferID = #GolferID;"
If Not Validation() Then
'Actually the input should be validated before we get here
MessageBox.Show("Did not pass validation. Correct the input")
Return
End If
Using cn As New MySqlConnection("Your connection string")
Using cmd As New MySqlCommand(strSelect, cn)
cmd.Parameters.Add("#FirstName", MySqlDbType.VarChar).Value = txtFirstName.Text
cmd.Parameters.Add("#LastName", MySqlDbType.VarChar).Value = txtLastName.Text
cmd.Parameters.Add("#Address", MySqlDbType.VarChar).Value = txtAddress.Text
cmd.Parameters.Add("#City", MySqlDbType.VarChar).Value = txtCity.Text
cmd.Parameters.Add("#State", MySqlDbType.VarChar).Value = txtState.Text
cmd.Parameters.Add("#Zip", MySqlDbType.VarChar).Value = txtZip.Text
cmd.Parameters.Add("#Phone", MySqlDbType.VarChar).Value = txtPhoneNumber.Text
cmd.Parameters.Add("#EMail", MySqlDbType.VarChar).Value = txtEmail.Text
'Are you sure you have set the .ValueMember of the combo boxes?
cmd.Parameters.Add("#ShirtSize", MySqlDbType.VarChar).Value = cboShirtSizes.SelectedValue.ToString
cmd.Parameters.Add("#Gender", MySqlDbType.VarChar).Value = cboGenders.SelectedValue.ToString
'Are your sure that intGolferID is not a number
cmd.Parameters.Add("#GolferID", MySqlDbType.Int32).Value = cboGolfers.SelectedValue
cn.Open()
intRowsAffected = cmd.ExecuteNonQuery()
End Using
End Using
If intRowsAffected = 1 Then
MessageBox.Show("Update successful")
Else
MessageBox.Show("Update failed")
End If
frmManageGolfers.Show() 'I can't image why you would try to send a button and the button's event args to the Load event of another form
End Sub
I somehow can't insert data into my MySQL database but I know there's no trouble with the query cause there is no error message and it can make it as far as the Success message box. I think the query is right for MySQL but it is not the specific one that I should use for INSERT INTO.
Here's my code:
Imports MySql.Data.MySqlClient
Public Class Register
Dim ServerString As String = "Server=localhost; UserId =root; Password = ; Database = gym;"
Dim MysqlConn As MySqlConnection = New MySqlConnection
Dim COMMAND As MySqlCommand
Dim password, pass As String
Dim member As Integer
Private Sub Register_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.CenterToParent()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MysqlConn.ConnectionString = ServerString
Dim READER As MySqlDataReader
password = TextBox2.Text
pass = TextBox3.Text
confirm(password, pass)
If TextBox1.Text = Nothing Or TextBox2.Text = Nothing Or TextBox3.Text = Nothing Or TextBox4.Text = Nothing Or TextBox5.Text = Nothing Or TextBox6.Text = Nothing Or DateTimePicker1.Text = Nothing Or RadioButton1.Checked = False And RadioButton2.Checked = False Then
MsgBox("Please Fill your Information Completely")
Else
MysqlConn.ConnectionString = ServerString
Try
MysqlConn.Open()
Dim query As String
query = "select * from gym.user where user_name ='" & TextBox1.Text & "'"
COMMAND = New MySqlCommand(query, MysqlConn)
READER = COMMAND.ExecuteReader
Dim count As Integer
While READER.Read
count = count + 1
End While
MysqlConn.Close()
If count > 0 Then
MsgBox("User Already Exists")
Else
MysqlConn.Open()
query = "INSERT INTO gym.user(user_name,user_password,user_firstname,user_lastname,user_birthday,user_contact,user_membership) VALUES ('" & TextBox1.Text & "', md5('" & TextBox2.Text & "') ,'" & TextBox4.Text & "','" & TextBox5.Text & "','" & DateTimePicker1.Value.Date & "','" & TextBox6.Text & "','" & member & "')"
COMMAND = New MySqlCommand(query, MysqlConn)
MsgBox("USER REGISTERED")
MysqlConn.Close()
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
MysqlConn.Dispose()
End Try
End If
End Sub
You're missing ExecuteNonQuery statement:
query = "INSERT INTO gym.user(user_name,user_password,user_firstname,user_lastname,user_birthday,user_contact,user_membership) VALUES ('" & TextBox1.Text & "', md5('" & TextBox2.Text & "') ,'" & TextBox4.Text & "','" & TextBox5.Text & "','" & DateTimePicker1.Value.Date & "','" & TextBox6.Text & "','" & member & "')"
COMMAND = New MySqlCommand(query, MysqlConn)
COMMAND.ExecuteNonQuery()
Recently i was trying to display data on datagridview but every time there is a new entry the DGV (datagridview) was not refreshing. I made a new method called showtable but when i search i use to get the database names insted of moded names in the code for example tax to TAX and so on..
This is the code:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
konekcija = New MySqlConnection
konekcija.ConnectionString =
"server=localhost;userid=root;password=root;database=baza"
Dim READER As MySqlDataReader
Try
Dim kupovnacena As Double
Dim prodaznacena As Double
kupovnacena = TextBoxKupovna.Text
prodaznacena = TextBoxProdazna.Text
If kupovnacena > prodaznacena Then
MessageBox.Show("Продажната цена не може да биде помала од куповната !")
TextBoxKupovna.Text = ""
TextBoxProdazna.Text = ""
End If
konekcija.Open()
If TextBoxBarkod.Text = "" Then
MessageBox.Show("Внеси баркод/шифра")
End If
If TextBoxNaziv.Text = "" Then
MessageBox.Show("Внеси назив на артиклот")
End If
If TextBoxKupovna.Text = "" Then
MessageBox.Show("Внеси куповна цена на артиклот")
End If
If TextBoxProdazna.Text = "" Then
MessageBox.Show("Внеси продажна цена на артиклот")
TextBoxProdazna.Text = Focus()
End If
Dim Query As String
Query = "insert into baza.artikli(id,barkod,naziv,kupovna,prodazna,opis,kolicina,proizvoditel,ddv,makpr) values ('" & TextBoxID.Text & "','" & TextBoxBarkod.Text & "','" & TextBoxNaziv.Text & "','" & TextBoxKupovna.Text & "','" & TextBoxProdazna.Text & "','" & TextBoxOpis.Text & "','" & TextBoxKolicina.Text & "','" & TextBoxProiz.Text & "','" & ddv & "','" & makpr & "')"
COMMAND = New MySqlCommand(Query, konekcija)
READER = COMMAND.ExecuteReader
MessageBox.Show("Артиклот е успешно ажуриран !")
TextBoxBarkod.Text = ""
TextBoxKupovna.Text = ""
TextBoxNaziv.Text = ""
TextBoxOpis.Text = ""
TextBoxProdazna.Text = ""
TextBoxKolicina.Text = ""
TextBoxID.Text = ""
TextBoxProiz.Text = ""
konekcija.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
konekcija.Dispose()
datagridview1.refresh()
End Try
End Sub
When I insert a null it shows an error in my code. Can I try and catch it? I don't know how.
Call Connects()
MySqlCmd = New MySqlCommand
MySqlCmd.Connection = Myconnect
MySqlCmd.CommandText = "Select ID,ItemName,Quantity,ItemDesc,SuppInfo,datee from item "
MyDA = New MySqlDataAdapter
myDataTable = New DataTable
MyDA.SelectCommand = MySqlCmd
MyDA.Fill(myDataTable)
MySqlCmd = New MySqlCommand
MySqlCmd.Connection = Myconnect
MySqlCmd.CommandText = "INSERT INTO item(ID,ItemName,Quantity,ItemDesc,SuppInfo,Po_Number,datee) VALUES('" & TextBox7.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "','" & TextBox6.Text & "',CURRENT_TIMESTAMP)"
MySqlCmd.ExecuteNonQuery()
MsgBox("New working", MsgBoxStyle.Information)
Is there anything I can do?
Here is a screenshot which shows the error:
Check your value of TextBox3.Text and if it cannot be parsed to int, replace it with 0. If you want insert NULL specify it precisely, not with empty string.
If Label30.Text = 1 Then
Try
If TextBox7.Text = "" Or TextBox2.Text = "" Or TextBox3.Text = "" Or TextBox4.Text = "" Or TextBox5.Text = "" Or TextBox6.Text = "" Then
MessageBox.Show("ERROR!")
ElseIf TextBox7.TextLength > 0 And TextBox2.TextLength > 0 And TextBox3.TextLength > 0 And TextBox4.TextLength > 0 And TextBox5.TextLength > 0 And TextBox6.TextLength > 0 Then
Call Connects()
MySqlCmd = New MySqlCommand
MySqlCmd.Connection = Myconnect
MySqlCmd.CommandText = "Select ID,ItemName,Quantity,ItemDesc,SuppInfo,datee from item "
MyDA = New MySqlDataAdapter
myDataTable = New DataTable
MyDA.SelectCommand = MySqlCmd
MyDA.Fill(myDataTable)
its working now thankyou :) this is how i solve my own problem.
Here's the code of my button_click:
Private Sub Button10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button10.Click
Dim conn As New MySqlConnection
Dim cmd As New MySqlCommand
Dim dr As MySqlDataReader
conn.ConnectionString = "server = localhost; user id = root; database = db; password = root"
cmd.Connection = conn
conn.Open()
cmd.CommandText = " SELECT * FROM candidate WHERE idn = '" & TextBox4.Text & "'"
dr = cmd.ExecuteReader
If dr.HasRows Then
MessageBox.Show("Entry I.D. No. already exist", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
ElseIf TextBox4.Text = "" Or TextBox5.Text = "" Or TextBox6.Text = "" Or TextBox7.Text = "" Or ComboBox1.Text = "" Or TextBox3.Text = "" Then
MessageBox.Show("Please complete the required fields..", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Else
conn.Close()
con.ConnectionString = "server = localhost; user id = root; database = db; password = root"
cmd.Connection = con
con.Open()
Dim sqlQuery As String = "INSERT INTO candidate(idn,cfname,cmname,clname,cyr,sec,vyear,votes,pword) VALUES('" & TextBox4.Text & "','" & TextBox5.Text & "','" & TextBox6.Text & "','" & TextBox7.Text & "','" & ComboBox1.Text & "','" & TextBox3.Text & "',CONCAT(YEAR(NOW()),'-',(YEAR(NOW()) + 1),'0','" & TextBox2.Text & "')"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = con
.ExecuteNonQuery()
End With
MsgBox("Record Inserted")
End If
End Sub
what's wrong with my INSERT query? I can't seem to find anything wrong here, but VB.NET says it has error in " at line 1?
"INSERT INTO candidate(vyear) VALUES(CONCAT(YEAR(NOW()),'-',(YEAR(NOW()) + 1))"
There is a unbalanced open parenthesis before the second YEAR. Need to remove it
"INSERT INTO candidate(vyear) VALUES( CONCAT(YEAR(NOW()),'-',YEAR(NOW()) + 1) )"
Looking at the updated code you really need to start to use parameterized queries
Using con = new MySqlConnection(......)
Using cmd = con.CreateCommand()
con.Open()
Dim sqlQuery As String = "INSERT INTO candidate " & _
"(idn,cfname,cmname,clname,cyr,sec,vyear,votes,pword) VALUES(" & _
"#idn, #cfname, #cmname, #clname, #cyr, #sec, " & _
"CONCAT(YEAR(NOW()),'-',YEAR(NOW()) + 1), " & _
"#votes, #pword"
With cmd
.CommandText = sqlQuery
' is idn an integer field, then pass it as integer.
' instead if it is an autoincrement then remove it and let the db calculate for you
.Parameters.AddWithValue("#idn", Convert.ToInt32(TextBox4.Text))
.Parameters.AddWithValue("#cfname, TextBox5.Text)
.... and so on for every placeholder in the parameterized text above
.ExecuteNonQuery()
End With
MsgBox("Record Inserted")
End Using
End Using