How to have an error handler that when I enter an ID in the text box and that ID is already existed in the database it will say. "ID already existed"
Here is my code
Public Class frmPawn
Dim ds As DataSet
Dim da As MySqlDataAdapter
Dim cmd As New MySqlCommand
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim con As New MySqlConnection("host=localhost; username=root; password=; database=pawnshop")
con.Open()
cmd.Connection = con
ds = New DataSet
da = New MySqlDataAdapter("insert into clients (clientid, fname, mname, lname, address, city, prov, zip, contact, birth, sex) values('" & txtId.Text & "','" & txtFname.Text & "','" & txtMname.Text & "','" & txtLname.Text & "','" & txtAddress.Text & "','" & txtCity.Text & "','" & txtProv.Text & "','" & txtZip.Text & "','" & txtContact.Text & "','" & DateTimePicker_DOB.Text & "','" & lblSex.Text & "')", con)
da.Fill(ds, "clients")
End Sub
End Class
I will not discuss how you should really design your system. But here is what you directly asked for
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
' your code here
Catch mySqlEx As MySqlExeption
' Here handle MySql Exceptions
If mySqlEx.Number = 1068 Then
. . . . .
' Exception number reference:
' http://dev.mysql.com/doc/refman/5.6/en/error-messages-server.html
Catch ex As Exception
' Here handle any other Exceptions
End Try
End Sub
As you see, you can use MySql for .Net documentation to get all the exception info, which you then handle in your code. The error you receive, I believe the code is 1068. Once you have this code running, you can put break point and check, what the code you receiving and then handle it.
You Can try to select a row from your databse with that said ID, if anything is selected than it already exists, otherwise you can run your code.
Related
I'm trying to insert data to MySql using vb.net. When I try to insert I've got the error. Please Help me.
Private Sub addEmp_Click(sender As Object, e As EventArgs) Handles addEmp.Click
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString =
"server=localhost;userid=root;password=;database=vbdb"
Dim READER As MySqlDataReader
Dim birthDate As String = bDay.Value.ToString("yyyy/mm/dd")
Dim dateHired As String = dHired.Value.ToString("yyyy/mm/dd")
Try
MysqlConn.Open()
Dim Query As String
Query = "insert into vbdb.employee_info (Last_Name, First_Name, Middle_Name, Gender, Birthdate, Address, Contact, Position, Emp_Type, Email, Date_Hired) values ('" & firstName.Text & "','" & lastName.Text & "','" & middleName.Text & "','" & gender.Text & "','" & birthDate & "','" & gender.Text & "','" & address.Text & "','" & contact.Text & "','" & position.SelectedItem.Text & "','" & type.SelectedItem.Text & "','" & email.Text & "','" & dateHired & "')"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = Command.ExecuteReader
MessageBox.Show("Data Saved")
MysqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
End Sub
You're using position.SelectedItem.Text. Presumably position is a ComboBox or ListBox and you have bound it to some list. Presumably the property or column that you have specified via the ValueMember contains Strings. That means that position.SelectedItem is a String and you are trying to access a Text member that doesn't exist.
For one thing, you should turn Option Strict On. That code wouldn't even compile then. That would mean that, if position.SelectedItem is a String, you would have to cast it as that type, probably using CStr. If it wasn't already obvious that you already had the String you needed, the compiler would tell you without your having to run the project that type String had no Text property.
Im a newbie in VB2010 & in MYSQL Database.
I have 2 database one on MS SQL 2008 (BigData) and another on Mysql. I have written some code in VB2010 to fetch data from SQL2008 and insert into MySQL. My goal is to transfer all data from MS SQL to MySQL as quick as I can thats why I created a simple vb script that will act as middleware to transfer data from MS SQL to MySQL.
My Headache is, almost 1 hour to transfer the 28,000 records from MS SQL to MySQL database. Is there any easiest way to transfer the data or I need to enhance my VBScript program. Please help to improve my VBScript below.
Thank you in advance.
Imports MySql.Data.MySqlClient
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Dim SQLConnectionSQL As MySqlConnection = New MySqlConnection
Dim connectionStringSQL As String = "Data Source=solomon;Initial Catalog=testapp;Persist Security Info=True;User ID=sa;Password=Passw0rd"
Dim connectionString As String = "Server=192.168.1.199; User Id=gil; Password=Passw0rd; Database=testapp"
Dim SQLConnection As MySqlConnection = New MySqlConnection
Dim oDt_sched As New DataTable()
Private Sub btnRetrieve_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRetrieve.Click
Dim con_Solomon As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim sql As String
Dim str_carSql As String
lblCounter.Text = 0
con_Solomon = "Data Source=solomon;Initial Catalog=MARYLANDAPP;Persist Security Info=True;User ID=sa;Password=Passw0rd"
sql = "SELECT LTRIM(RTRIM(DocType)) as DocType, LTRIM(RTRIM(cust_classID)) as cust_classID, LTRIM(RTRIM(salesman)) as salesman, LTRIM(RTRIM(CustId)) as CustId, LTRIM(RTRIM(name)) as name, LTRIM(RTRIM(ClassID)) as ClassID, LTRIM(RTRIM(invoice_no)) AS refnbr, invoice_delv_date AS Delv_DocDate, Age, AR_Amount, LTRIM(RTRIM(STATUS)) as STATUS, LTRIM(RTRIM(AGE_GROUP)) as AGE_GROUP, LTRIM(RTRIM(company)) AS comp, '' AS Deposit_Date, Credit_Limit, LTRIM(RTRIM(Terms)) as Terms, LTRIM(RTRIM(customer_name)) AS ShipName, LTRIM(RTRIM(PO_Number)) as PO_Number, LTRIM(RTRIM(Kob)) as Kob, LTRIM(RTRIM(check_date)) as check_date FROM a_aging_ardoc_report"
connection = New SqlConnection(con_Solomon)
Try
connection.Open()
command = New SqlCommand(sql, connection)
command.CommandTimeout = 420
adapter.SelectCommand = command
adapter.Fill(ds, "PO_Monitoring")
adapter.Dispose()
command.Dispose()
connection.Close()
''****** MYSQL CONNECTION *****
SQLConnection = New MySqlConnection()
SQLConnection.ConnectionString = connectionString
SQLConnection.Open()
Dim sqlCommand As New MySqlCommand
Dim delv_docdate, check_date
For a = 0 To ds.Tables(0).Rows.Count - 1
With ds.Tables(0).Rows(a)
If Not IsDBNull(.Item(7)) Then
delv_docdate = .Item(7)
Else
delv_docdate = ""
End If
If Not IsDBNull(.Item(19)) Then
check_date = .Item(19)
Else
check_date = ""
End If
str_carSql = "insert into agingreportsummary(doctype,cust_classid,salesman,custId,name,classid,refnbr,delv_docdate,age,ar_amount,status,age_group,comp,credit_limit,terms,shipname,po_number,kob,check_date) " & _
"VALUES('" & .Item(0) & "','" & .Item(1) & "','" & Replace(.Item(2), "'", "") & "','" & .Item(3) & "','" & Replace(.Item(4), "'", "") & "','" & Replace(.Item(5), "'", "") & "','" & .Item(6) & "','" & delv_docdate & "'," & Replace(.Item(8), ",", "") & "," & Replace(.Item(9), ",", "") & ",'" & Replace(.Item(10), "'", "") & "','" & .Item(11) & "','" & .Item(12) & "','" & .Item(14) & "','" & .Item(15) & "','" & Replace(.Item(16), "'", "") & "','" & Replace(.Item(17), "'", "") & "','" & .Item(18) & "','" & check_date & "');"
End With
sqlCommand.Connection = SQLConnection
sqlCommand.CommandText = str_carSql
sqlCommand.ExecuteNonQuery()
Next a
SQLConnection.Close()
MsgBox("Finish")
Catch ex As Exception
MsgBox(str_carSql)
MsgBox(ex.Message)
End Try
End Sub
End Class
You can try using a parameterised query instead of building a query for each row. That should improve things slightly since the statement wouldn't need to be prepared every time.
Add all the required parameters to the command.
Set the command text once, and change it to use parameters.
Inside the loop you would only set the parameter values and call the executenonquery method
This would have the added benefit of not being vulnerable to sql injection.
Hope that helps
I have an issue here .. i cant save combobox content into my table ... all other data are successfully saved but the combo box is saved either 1 or zero .. what seems to be wrong?
My tables are designed through navicat .. does this have anything to do with my choice of data type? knowing that I chose the data type to be Text
This is my code and it shows no run errors
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim conStr As String = ("Data Source=localhost;user id=root;password=123456;database=sam;")
Try
Dim con As New MySqlConnection(conStr)
Dim cmd As MySqlCommand
For i = 0 To ComboBox4.Items.Count
con.Open()
Dim sqls As String = "INSERT INTO initial_nom(f_name,s_name,th_name,fo_name,app_no,adm_type) VALUES('" & TextBox1.Text & "', '" & TextBox2.Text & "', '" & TextBox3.Text & "', '" & TextBox4.Text & "'," & TextBox5.Text & ",'" & ComboBox4.SelectedIndex.ToString & "')"
cmd = New MySqlCommand(sqls, con)
cmd.ExecuteNonQuery()
Next
Catch ex As Exception
MsgBox("Error in saving to Database. Error is :" & ex.Message)
End Try
End Sub
SelectedIndex is integer which point to index of the selected item. Assuming that combobox's data source contains collection of string, try to use SelectedItem instead, type-cast it to string :
DirectCast(ComboBox4.SelectedItem, String)
What's the most efficient way to execute two queries at the same time?
I want to execute two INSERT sql queries (different tables) simultaneously when I click the submit button. is it possible?
Here's what I did:
Dim conn As New MySqlConnection("Server = localhost; user id = root;password = ; database = ddap_hr")
Dim sqlQuery1 As String = "INSERT INTO applicants VALUES ( '" & lblID.Text & "' , '" & txtLName.Text & "','" & txtFName.Text & "','" & txtMName.Text & "','" & cmboGender.Text & "','" & mtxtAge.Text & "','" & dtpBdate.Value & "','" & cmboStatus.Text & "','" & txtSSS.Text & "','" & txtTin.Text & "','" & txtReligion.Text & "','" & txtAddress.Text & "','" & mtxtContactNum.Text & "','" & txtEmail.Text & "')"
Dim sqlQuery2 As String = "INSERT INTO appli_idgen(Lzero) VALUES ('" & lblNum.Text & "')"
Dim cmd1 As New MySqlCommand(sqlQuery1)
Dim cmd2 As New MySqlCommand(sqlQuery2)
Dim rdr As MySqlDataReader
Dim ConfirmMsg = MessageBox.Show("Are all the datas correct?" & Environment.NewLine & " • Last Name: " & txtLName.Text & Environment.NewLine & " • First Name: " & txtFName.Text & Environment.NewLine & " • Middle Name: " & txtMName.Text & Environment.NewLine & " • Gender: " & cmboGender.Text & Environment.NewLine & " • Age: " & mtxtAge.Text & Environment.NewLine & " • Date of Birth: " & dtpBdate.Text & Environment.NewLine & " • Status: " & cmboStatus.Text & Environment.NewLine & " • SSS: " & txtSSS.Text & Environment.NewLine & " • TIN: " & txtTin.Text & Environment.NewLine & " • Religion: " & txtReligion.Text & Environment.NewLine & " • Address: " & txtAddress.Text & Environment.NewLine & " • Contact Number: " & mtxtContactNum.Text & Environment.NewLine & " • E-mail: " & txtEmail.Text & Environment.NewLine, "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, 0, False)
If ConfirmMsg = MsgBoxResult.Yes Then
Try
Try
cmd1.Connection = conn
conn.Open()
cmd1.ExecuteNonQuery()
rdr = cmd.ExecuteReader
rdr.Read()
Catch ex1 As MySqlException
MsgBox(ex1.Message.ToString)
Finally
conn.Close()
End Try
Try
cmd2.Connection = conn
conn.Open()
cmd2.ExecuteNonQuery()
rdr = cmd.ExecuteReader
rdr.Read()
Catch ex2 As MySqlException
MsgBox(ex2.Message.ToString)
Finally
conn.Close()
End Try
Catch ex As MySqlException
MsgBox(ex.Message.ToString)
Finally
Dim addAnother = MessageBox.Show("Do you want to add another applicant?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, 0, False)
If addAnother = MsgBoxResult.No Then
Me.Close()
Main_home.Refresh()
End If
End Try
End If
I want to reduce the line of codes as much sa possible. I need your help. btw I'm using MySql. Sorry cause I'm new in VB. Thanks in advance.
It would help if you've shown us what you've tried, friend.
As it stands, you can create a subroutine which will execute Nonquery to MySQL then CALL that sub TWICE on any trigger(button, checkbox, etc.):
Note: this requires you know how to use the MySQL connector for .NET You can look for more on that here
Public Sub MyNonQuery(ByVal SQCommand as String)
Dim conn As New MySqlConnection("server=your server ip; port=the server port; uid='your user id';password ='your password';")
Dim SQLCMD as new MySqlCommand(SQCommand, conn)
conn.open()
SQLCMD.ExecuteNonQuery()
conn.close()
End Sub
Now you can use this sub in the following manner(s):
CALL it twice
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
MyNonQuery("Insert into db.tbl1 values(...);")
MyNonQuery("Insert into db.tbl2 values(...);")
End Sub
On a single call, Send TWO SQL commands
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
MyNonQuery("Insert into db.tbl1 values(...); Insert into db.tbl2 values(...);")
End Sub
Remember to properly Clean the data from the user though, to prevent SQL Injection attacks. Ultimately I would suggest you look into studying Stored Procedures
To answer the question you could try and start two threads running one immeddiately after the other. This is effectively having them run at the same time.
Private Sub Button36_Click(sender As Object, e As EventArgs) Handles Button36.Click
Dim t1 As New Threading.Thread(AddressOf Insert1)
Dim t2 As New Threading.Thread(AddressOf Insert2)
t1.Start()
t2.Start()
End Sub
Private Sub Insert1()
'do insert here
End Sub
Private Sub Insert2()
'do insert here
End Sub
Whether you will get any performance improvement I doubt.
im late but try this, hope it helps
Public Sub CreateCommand(ByVal connectionString As String)
Using connection As New SqlConnection(connectionString)
Dim query As String = "INSERT INTO tbl_example ..."
Dim query2 As String = "INSERT INTO tbl_add ..."
Dim QueryString As String = String.Concat(query,";",query2)
Dim command As New SqlCommand(QueryString, connection)
command.Connection.Open()
command.ExecuteNonQuery()
End Using
End Sub
Is this web or windows based?
Windows forms - do as above comment
'Web forms
Private Sub SubmitButton_Click(sender As Object, e As EventArgs) Handles SubmitButton.Click
'do insert 1 here
'do insert 2 here
End Sub
I am new to VB programming and have come across an problem:( after a couple of days trying to resolve this need some help!
I am trying to pass some information from a VB form to my MySQL database. i have named all the textbox's the same as the field in the database and checked all my database fields and textbox names which are all correct.
When i try to enter information into a form I sometimes get an error at the .executeNonQuery section of the code.
To test, I outputted the SQLStatement string to a textbox ( which pulled through all the fields from the textboxes correctly) then manually inputted the completed SQL query into the database and it worked. But when I try to do this in one go it seems to fail if there is too much text ( if i enter 'a' into each field it works). Are they limits to the size of the SQL query that can be passed from VB?? all the MySql database fields are set to text with no size limits.
Thanks in advance!!!
Public Sub SaveQuote(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
SQLConnection.Close()
MsgBox("successfully Added!")
SQLConnection.Dispose()
End Sub
Private Sub CmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdSave.Click
Dim SQLstatement As String = "INSERT INTO laptopstock(forename,surname,emailaddress,contactnumber,quotedate,manufacturer,model,os,battery,drive,defects) VALUES('" & forename.Text & "','" & surname.Text & "','" & emailaddress.Text & "','" & contactnumber.Text & "', CURDATE(),'" & manufacturer.Text & "','" & modelnumber.Text & "','" & os.Text & "','" & batterycondition.Text & "','" & drivetype.Text & "','" & defects.Text & "')"
SaveQuote(SQLstatement)
End Sub
'Test SQL query
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim testSQLstatement As String = "INSERT INTO laptopstock(forename,surname,emailaddress,contactnumber,quotedate,manufacturer,model,os,battery,drive,defects) VALUES('" & forename.Text & "','" & surname.Text & "','" & emailaddress.Text & "','" & contactnumber.Text & "', CURDATE(),'" & manufacturer.Text & "','" & modelnumber.Text & "','" & os.Text & "','" & batterycondition.Text & "','" & drivetype.Text & "','" & defects.Text & "')"
testbox.Text = testSQLstatement
End Sub
here is the output from testSQLstatement = testbox.text
INSERT INTO laptopstock(forename,surname,emailaddress,contactnumber,quotedate,manufacturer,model,os,battery,drive,defects) VALUES('Joe','Bloggs','J.bloggs#jbloggs.com','07777777777', CURDATE(),'Sony','Vaio','Windows 7 Pro','Poor','DVD-Rom','Faulty Screen')
from what i can see it is correctly formatted and when i enter this directly into a query on the MySql server a record is created
Does your application SQL login have insert rights on this table? Try executing a grant statment in SQL console directly:
"grant insert on dbo.laptopstock to (add you application login here)"
Also, I why are you passing the SQLStatement byref? You are not modifying it, so use byval. This shouldn't impact the code, but is a good practice.
I see you state that sometimes you get an error, so we can asume it is working code. That leads me to believe it is in your input data. Do the fields accept nulls? Are they the right format? Also, one of these things is not like the others, the date. You are passing the curdate() function in the insert. If the fields are all strings like you mention, then you are performing an implicit conversion from date to string. You could as easily built the insert string using the Vb.Net equivalent. (Date.Now.ToString).
Lastly, it is hard to debug this without more detailed information about the
error. As you have not posted code for your SQLConnection and MySLCommand objects (sure you don't mean MySQLCommand as New SQLCommand) I have to assume they work.