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.
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.
I've been trying for days but I just can't someone please help me.
My mySql database has an image column, and whenever I input data without an image it won't input the data. There might be a problem with my code but I don't know what to put. I need to be able to input data even if the user doesn't put an image in the picture box. Thank you!
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
On Error Resume Next
cn.Open()
Using cmd As New SqlClient.SqlCommand("INSERT INTO tblMembers(name, contactno, address, birthday, baptism, ministry, memberpic)VALUES('" & txtName.Text & "','" & txtContactNo.Text & "','" & txtAddress.Text & "','" & dtpBirthday.Text & "','" & dtpBaptism.Text & "','" & txtMinistry.Text & "',#memberpic)", cn)
cmd.Parameters.Add(New SqlClient.SqlParameter("#memberpic", SqlDbType.Image)).Value = IO.File.ReadAllBytes(a.FileName)
i = cmd.ExecuteNonQuery
End Using
If (i > 0) Then
MsgBox("Save record successfully!", MsgBoxStyle.Information, "Save")
Clear()
End If
cn.Close()
ShowRecord()
End Sub
Wrap line 5 of your snippet with an if. The if should be something like "if image was uploaded" or "if a.fileName is not null"
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.
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
is there any possible way to execute this without getting this error "There is already an open DataReader associated with this Connection which must be closed first." i already tried using "dr.close()" and i get another error that says "Invalid attempt to Read when reader is closed." can you help me out?
Heres my code:
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Label2.Text = AllPicker1.Text
Label3.Text = AllPicker2.Text
If AllPicker1.Value >= AllPicker2.Value Then
MsgBox("End Date Must be Greater!")
Else
Dim SQLstatement As String = "SELECT * FROM tblStudInfo,tbl_studentLog WHERE tblStudInfo.StudID = tbl_studentLog.StudentNumber AND tbl_studentLog.LoginDate BETWEEN '" & AllPicker1.Text & "' AND '" & AllPicker2.Text & "'"
OpenData(SQLstatement)
End If
End Sub
Public Sub OpenData(ByRef SQLstatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLstatement
.CommandType = CommandType.Text
.Connection = SqlConnection
dr = .ExecuteReader()
End With
While dr.Read
Dim SQLstatementSave As String = "INSERT INTO tbl_report (RepStudNo,RepName,RepCourse,RepDept,RepLogTime,RepLogdate) VALUES ('" & dr("StudID") & "','" & dr("Name") & "','" & dr("Course") & "','" & dr("Dept") & "','" & dr("LoginTime") & "','" & dr("LoginDate") & "') "
dr.Close()
Save(SQLstatementSave)
End While
SqlConnection.Close()
SqlConnection.Dispose()
SqlConnection.Open()
End Sub
Public Sub Save(ByRef SQLstatementSave As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLstatementSave
.CommandType = CommandType.Text
.Connection = SqlConnection
.ExecuteNonQuery()
End With
SqlConnection.Close()
SqlConnection.Dispose()
SqlConnection.Open()
End Sub
End Class
It seems you are using only one SqlConnection. For most database systems you cannot reuse the connection while you are reading from it. You can either read all data into memory / DataTable and work on the rows after that or use a different SqlConnection for your Inserts.
When working with SqlConnections, Readers and Commands I find the Using Statement very helpful to visualize object usage and creation.
We can reduce this down to a single query:
INSERT INTO tbl_report
(RepStudNo,RepName,RepCourse,RepDept,RepLogTime,RepLogdate)
SELECT StudID, Name, Course, Dept, LoginTime, LoginDate
FROM tblStudInfo
INNER JOIN tbl_studentLog ON tblStudInfo.StudID = tbl_studentLog.StudentNumber
WHERE tbl_studentLog.LoginDate BETWEEN #StartDate AND #EndDate
Note the use of the full INNER JOIN syntax. The older TableA,TableB syntax for joins should be avoided. Also note the use of placeholders for your dates. This is important.
Now I need to draw attention to a couple functions I saw: OpenData(), and Save().
Those two functions are fundamentally broken, because they force you to build your queries in a way that leaves you vulnerable to sql injection hacking. Someday soon, someone will put a value like this into a textbox that is included with a query:
';DROP Table tbl_studentLog;--
Think carefully about what would happen now if someone entered that into your AllPicker1.Text. It would be hard to do that to a date picker, but I'll bet you have other plain text fields that would allow this. The first character (single quote) in my proposed input would close the string literal in the query. The second character (semi-colon) would end the individual statement, but sql server won't stop executing code. The next set of characters make up an additional statement that would drop your table. The final two characters comment out anything that follows, to avoid sql server rejecting or not committing the command because of syntax errors. Yes, Sql Server will run that additional statement, if that is what you put in a textbox.
So, your methods as written are broken, because the only accept completed sql strings as input. Any function that calls into the database MUST also include a mechanism for accepting query parameters. You ultimately want to be running code more like this:
Public Sub CreateReport(ByVal StartDate As DateTime, ByVal EndDate As DateTime)
Dim sql As String = _
"INSERT INTO tbl_report " & _
" (RepStudNo,RepName,RepCourse,RepDept,RepLogTime,RepLogdate) " & _
" SELECT StudID, Name, Course, Dept, LoginTime, LoginDate " & _
" FROM tblStudInfo " & _
" INNER JOIN tbl_studentLog ON tblStudInfo.StudID = tbl_studentLog.StudentNumber " & _
" WHERE tbl_studentLog.LoginDate BETWEEN #StartDate AND #EndDate"
'.Net is designed such in most cases that you really do want a new SqlConnection for each query
'I know it's counter-intuitive, but it is the right way to do this
Using cn As New SqlConnection("Connection string"), _
cmd As New SqlCommand(sql, cn)
'Putting your data into the query using parameters like this is safe from injection attacks
cmd.Parameters.Add("#StartDate", SqlDbType.DateTime).Value = StartDate
cmd.Parameters.Add("#EndDate", SqlDbType.DateTime).Value = EndDate
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
One thing to point out here is that at first glance I don't close the connection. However, the Using block will ensure that the connection is closed promptly... even if an exception is thrown. Your existing code will leave the connection hanging in the case of a exception.
Also note that this neatly side-steps the whole issue of needing to execute a separate query while your reader is opened... but if you ever do really need to do this (it's rare), the answer is simple: use a separate connection.
Instead of:
Dim SQLstatementSave As String = "INSERT INTO tbl_report
(RepStudNo,RepName,RepCourse,RepDept,RepLogTime,RepLogdate)
VALUES ('" & dr("StudID") & "','" & etc.
Try using .ToString on your DR() references.
Dim SQLstatementSave As String = "INSERT INTO tbl_report
(RepStudNo,RepName,RepCourse,RepDept,RepLogTime,RepLogdate)
VALUES ('" & dr("StudID").ToString & "','" & etc.