MySQL / vb.NET: Check exisiting data before run the insert query - mysql

I'm using vb.net to create API (MySQL). I know how to run create API for insert, select, and update. Now, I want to create an API that before data insert, must check the data, either exist in the table or not. If exist, then cannot insert the data. Below is my current vb.net code:
<WebMethod()>
<ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=False, XmlSerializeString:=False)>
Public Sub TGWL_insertLoadingSV(bl_id As String, cont_size_id As String, straping As String)
Dim mySQLConnection As MySqlConnection = New MySqlConnection("Data Source=" & l_DB_SERVER & ";Initial Catalog=" & l_DB_NAME & ";User Id=" & l_DB_USER & ";Password=" & l_DB_PASS)
Dim myDataAdapter As MySqlDataAdapter
Dim myDataset As DataSet = New DataSet
Dim myJson As String = ""
Try
If bl_id.Length > 0 Or cont_size_id.Length > 0 Or straping.Length > 0 Then
Dim myResponse As New failResponceClass
myDataAdapter = New MySqlDataAdapter
myDataAdapter.InsertCommand = New MySqlCommand("BEGIN;
INSERT INTO wla_loading_sv (bl_id, cont_size_id)
VALUES ('" & bl_id & "', '" & cont_size_id & "');
INSERT INTO wla_special_req (bl_id, straping)
VALUES('" & bl_id & "', '" & straping & "');
COMMIT;")
myDataAdapter.InsertCommand.Connection = mySQLConnection
mySQLConnection.Open()
myDataAdapter.InsertCommand.ExecuteNonQuery()
mySQLConnection.Close()
myResponse.statusCode = 1
myResponse.errCode = ""
myResponse.title = l_Title_TGWLAppUser
myResponse.desc = "TGWL App User"
Me.Context.Response.ContentType = "application/json; charset=utf-8"
Me.Context.Response.Write(JsonConvert.SerializeObject(myResponse))
Else
Dim myFailedResponce As New failResponceClass
myFailedResponce.statusCode = 0
myFailedResponce.errCode = "R01"
myFailedResponce.title = l_Title_TGWLAppUser
myFailedResponce.desc = "Missing parmeter."
Me.Context.Response.ContentType = "application/json; charset=utf-8"
Me.Context.Response.Write(JsonConvert.SerializeObject(myFailedResponce))
End If
Catch ex As SoapException
Throw ex
Finally
MySqlConnection.ClearPool(mySQLConnection)
MySqlConnection.ClearAllPools()
mySQLConnection.Close()
mySQLConnection.Dispose()
End Try
End Sub
Thus, how do I want to make sure that the bl_id does not exist at wla_loading_sv table? I want to make it in one API. Can someone help?

Related

How to remove row of data gridview in vb.net?

I want to remove the rows of data gridview after use a query sql from database
i use this code
Try
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US")
Dim strConn As String
strConn = "DRIVER=PostgreSQL ANSI;SERVER=127.0.0.1;PORT=5432;UID=postgres;Password=azerty79;DATABASE=" & ComboBox2.Text & ";pwd=postgres;ReadOnly=0"
'strConn = "DRIVER={PostgreSQL ANSI};UID=postgres;pwd=postgres;LowerCaseIdentifier=0;UseServerSidePrepare=0;ByteaAsLongVarBinary=0;"
'strConn = "dsn=test;uid=postgres;pwd=postgres"
Dim cnDb As OdbcConnection
Dim dsDB As New DataSet
Dim adDb As OdbcDataAdapter
Dim cbDb As OdbcCommandBuilder
Dim cmd As OdbcCommand
Dim cmd1 As OdbcCommand
Dim adDb1 As OdbcDataAdapter
Dim dsDB1 As New DataSet
Dim dt As New DataTable
Dim pic As New PictureBox
cnDb = New OdbcConnection(strConn)
cnDb.Open()
dsDB = New DataSet
adDb = New OdbcDataAdapter
cbDb = New OdbcCommandBuilder(adDb)
'cmd.Parameters.Add("#id", OdbcType.NVarChar, "1")
For i = 1 To 3
' Create the SelectCommand.
cmd = New OdbcCommand("select b.id_detail_polygon,b.mappe_3,b.type_d_affaire,b.consistance,b.nbr_borne ,num_bornes,a.x,a.y,b.superficie_cs from point a right join (select (dp).path[1] d1,(dp).path[2] d2,(dp).geom d3 from (select st_dumppoints(geom) dp from polygon where id_detail_polygon ='" & i & "')a)dptable on st_equals(a.geom,dptable.d3),polygon b where id_detail_polygon='" & i & "'", cnDb) ' & _
'"WHERE id = ? ", cnDb)
cmd1 = New OdbcCommand("SELECT num_bornes,x,y FROM point RIGHT JOIN (SELECT (dp).path[1] As ringID,(dp).path[2] As pointID,(dp).geom ptgeom FROM (SELECT st_dumppoints(geom) dp FROM polygon WHERE id_detail_polygon='" & i & "' ) a) dptable ON ST_Equals(point.geom, dptable.ptgeom) ORDER BY dptable.pointID;", cnDb)
'cmd.Parameters.Add("#id", OdbcType.NVarChar, "1")
adDb = New OdbcDataAdapter(cmd)
adDb1 = New OdbcDataAdapter(cmd1)
adDb.Fill(dsDB, ComboBox1.Text)
adDb1.Fill(dsDB1, ComboBox1.Text)
DataGridView2.DataSource = dsDB
DataGridView3.DataSource = dsDB1
DataGridView2.DataMember = ComboBox1.Text
DataGridView3.DataMember = ComboBox1.Text
DataGridView2.DataSource = dsDB.DefaultViewManager
DataGridView3.DataSource = dsDB1.DefaultViewManager
Dim StrExport As String = ""
For Each R As DataGridViewRow In DataGridView3.Rows
For Each C As DataGridViewCell In R.Cells
If Not C.Value Is Nothing Then
StrExport &= C.Value.ToString & " "
Else
End If
Next
StrExport = StrExport.Substring(0, StrExport.Length - 1)
StrExport &= Environment.NewLine
Next
Dim fName As String = ""
SaveFileDialog1.InitialDirectory = "C:\Users\pc\Desktop\"
SaveFileDialog1.Filter = "dat files (*.dat)|*.dat"
SaveFileDialog1.FilterIndex = 2
SaveFileDialog1.Title = "dat"
SaveFileDialog1.RestoreDirectory = True
If (SaveFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK) Then
fName = SaveFileDialog1.FileName
End If
For j = 0 To 0
For x = 0 To DataGridView2.RowCount - 1
Dim tw As IO.TextWriter = New IO.StreamWriter(fName)
tw.Write(DataGridView2.Rows(j).Cells(0).Value & vbCr & vbLf & DataGridView2.Rows(j).Cells(1).Value & vbCr & vbLf & DataGridView2.Rows(j).Cells(2).Value & vbCr & vbLf & DataGridView2.Rows(j).Cells(3).Value & vbCr & vbLf & DataGridView2.Rows(j).Cells(4).Value & vbCr & vbLf & StrExport & " " & DataGridView2.Rows(j).Cells(8).Value)
tw.Close()
Next
Next
For Each row As DataGridViewRow In DataGridView2.Rows
DataGridView2.Rows.Remove(row)
Next
Next
Catch ex As Exception
MsgBox("ERROR :" + ex.Message)
End Try
MsgBox("Exported", vbInformation, "Successful")
But i get this problem below
Edit
Basing on your comment, I understand you don't want the data gone from the database bug instead from the grid. I would advise against using a dataset as you have done. A DataSet has a collection of DataTable objects that you can manipulate. I also see that you are removing every row in a For Each loop. You can remove these rows from the table or call the clear method on that table and you grid should reflect it. I have left the original answer to explain why this was happening. Edit
Without being able to tell what the error is, I'll just tell you that you cannot programmatically remove a row from a DataGridView if the DataSource is not an IBindingList with change event notification. OdbcDataAdapter does not implement IBindingList anywhere in its inheritance chain.
If you are not willing to change what you bind to, you can re-run the query to get the items and bind the grid again.

Inserting query results from MS SQL 2008 to MYSQL via VB2010

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

How do you insert a binary reader to string query for mysql?

I'm learning how to upload images into MySql database. Before you all get cranky and tell me that it's bad practice to upload images into mysql database, I AGREE WITH YOU, but it's for a school project and that's what the school wants.
This is what I found on the net and it works. But I would like to understand it more and maybe modify it to fit my custom subs. Also the datatype for the images is blob
Dim strFileName as String 'This is the file path
Dim con As MySqlConnection = New MySqlConnection(cnn.ConnectionString)
Dim cmd As MySqlCommand
Dim fs As FileStream
Dim br As BinaryReader
Dim FileName As String = strFileName.ToString
Dim ImageData() As Byte
fs = New FileStream(FileName, FileMode.Open, FileAccess.Read)
br = New BinaryReader(fs)
ImageData = br.ReadBytes(CType(fs.Length, Integer))
br.Close()
fs.Close()
If File.Exists(strFileName) = False Then MsgBox("Cannot locate file") : Return
Dim CmdString As String = "INSERT into tbl_maps(map_name,map_floor,map) Values('" & txtMapName.Text & "','" & cmbMapsFloor.Text & "',#Image)"
cmd = New MySqlCommand(CmdString, con)
cmd.Parameters.AddWithValue("Image", ImageData)
con.Open()
Now my question is, is there a way to insert ImageData into a string for the MySqlCommand? This is how I usually insert data into the database.
Public Sub RunQuery()
On Error Resume Next
dr.Close()
InitQuery()
cmd.ExecuteNonQuery()
End Sub
Public Sub InitQuery()
With cmd
.CommandText = sql
.Connection = cnn
End With
End Sub
Private Sub something()
sql = "INSERT into tbl_maps(map_name,map_floor) Values('" & txtMapName.Text & "','" & cmbMapsFloor.Text & "')"
RunQuery()
MsgBox("Data saved successfully") 'or some way to check the data inserted
End Sub
I was hoping for something that would maybe look like this
sql = "INSERT into tbl_maps(map_name,map_floor,map) Values('" & txtMapName.Text & "','" & cmbMapsFloor.Text & "','" & ImageData & "')"
RunQuery()
But I know that's not correct because sql is a string and ImageData is not. I'm just looking for a way to avoid using cmd.Parameters.AddWithValue("Image", ImageData) or at the very least integrate it into my RunQuery sub.
P.S.: Not that it really matters but I like 1 line code sets. Because I read lines like I read sentences. Example:
If RecordNotExist() = true then Msgbox("Record not found") : txtsearch.selectall() : txtsearch.focus() : return
Translation: If no records match the search query, search for something else.

Why do I keep getting this mysql error?

Hi stackoverflow people!
I have been recently developing a simple vb.net program that connects to a mysql database to register and login users with given credentials. I have used this code to register my users but I keep getting and error (below the code)
Dim insertUser As String = "INSERT INTO users(ID, username, password, email, verif)" _
& " VALUES('','" & Username.Text & "','" & Password.Text & "','" & Email.Text & "','" & currentRandString & "');"
Dim checkUsername As String = "SELECT * FROM users WHERE username='" & Username.Text & "'"
MysqlConn = New MySqlConnection()
MysqlConn.ConnectionString = mysqlconntxt4reg
MysqlConn.Open()
Dim myCommand As New MySqlCommand
myCommand.Connection = MysqlConn
myCommand.CommandText = checkUsername
myAdapter.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader
If myData.HasRows > 0 Then
MsgBox("Username Already In Use...", MsgBoxStyle.Critical, "Error")
myData.Close()
Else
myData.Close()
Dim myCommand2 As New MySqlCommand
myCommand2.Connection = MysqlConn
myCommand2.CommandText = insertUser
myAdapter.SelectCommand = myCommand2
Dim myData2 As MySqlDataReader
myData2 = myCommand2.ExecuteReader
Mail(Email.Text, currentRandString)
Me.Close()
myData2.Close()
End If
Catch myerror As MySqlException
MsgBox("Error While Connecting To Database:" & vbNewLine & vbNewLine & myerror.ToString, MsgBoxStyle.Critical, "Error")
Finally
MysqlConn.Dispose()
End Try
I have closed all my datareaders before opening other ones so I do not see why this does not work...
Error:
Link to Error Image
I would appreciate any help on this topic!
Thanks
Rodit
I would use the using statement around all the disposable objects to be sure that they release every references to the connection when they are no more needed, but looking at your code, I think you don't need at all the datareaders because you could resolve your problem just with the commands
Dim insertUser As String = "INSERT INTO users(username, password, email, verif)" _
& " VALUES(#p1, #p2,#p3,#p4)"
Dim checkUsername As String = "SELECT COUNT(*) FROM users WHERE username=#p1"
Using MysqlConn = New MySqlConnection(mysqlconntxt4reg)
Using myCommand = New MySqlCommand(checkUsername, MysqlConn)
MysqlConn.Open()
myCommand.Parameters.AddWithValue("#p1", Username.Text)
Dim result = myCommand.ExecuteScalar()
if result IsNot Nothing AndAlso Convert.ToInt32(result) > 0 Then
MsgBox("Username Already In Use...", MsgBoxStyle.Critical, "Error")
Else
Using myCommand2 = New MySqlCommand(insertUser, MysqlConn)
mycommand2.Parameters.AddWithValue("#p1",Username.Text)
mycommand2.Parameters.AddWithValue("#p2",Password.Text )
mycommand2.Parameters.AddWithValue("#p3",Email.Text)
mycommand2.Parameters.AddWithValue("#p4",currentRandString )
myCommand2.ExecuteNonQuery()
Mail(Email.Text, currentRandString)
End Using
End If
End Using
End Using
Of course I have replaced your string concatenations with a parameterized query. This is really an important thing to do to avoid Sql Injection
I have replaced the query that checks the user existence with a scalar operation that can be used with the command ExecuteScalar. Also, in the first query, it seems that you try to insert the field ID with an empty string. I think that the first field (ID) is an autonumber field and, in this case, you don't add it to the insert query and don't pass any value because the database will calculate that field for you.

The connection property has not been set or is null

When I run this function
For RepeatBooking = 1 To 51
dateConvertedDateToBook = dateDateToBook.Date
dateDateToBook = dateDateToBook.AddDays(7)
strDateToBook = dateConvertedDateToBook.ToString("yyyy-MM-dd")
Try
Dim command As MySqlCommand = New MySqlCommand
Dim sqlQuery As String = "INSERT INTO bookings SET Date=" & "'" & strDateToBook & "',RoomID='" & strComputerRoomToBook & "',Length='" & intNewBookingLength & "',Period='" & intNewStartPeriod & "',UserID='" & intid & "'"
Dim reader As MySqlDataReader
SQLConnection.Open()
command.CommandText = sqlQuery
command.Connection = SQLConnection
reader = command.ExecuteReader
SQLConnection.Close()
Catch excep As Exception
MsgBox(excep.ToString)
End Try
Next
in my program I get an error saying "The connection property has not been set or is null"
How can I get rid of this?
It goes to the exception when it gets to SQLconnection.Open()
I created the ServerString and MySQL connection at the top of the module like so:
Dim ServerString As String = "Server=localhost;User Id=root;Password=**********;Database=rooms"
Dim SQLConnection As MySqlConnection = New MySqlConnection
You are opening a connection without its property
It should be,
Dim SQLConnection As New MySqlConnection(ServerString)
SQLConnection.Open
Also, you may want to use the USING function so that your connection is properly closed.
It seems you are just inserting a bunch of values to your database and not retrieving anything so why do you use a DataReader?
Your code should be something like this:
Using SQLConnection = New MySqlConnection(ServerString)
SQLConnection.Open 'You should open a connection only once
For RepeatBooking = 1 To 51
dateConvertedDateToBook = dateDateToBook.Date
dateDateToBook = dateDateToBook.AddDays(7)
strDateToBook = dateConvertedDateToBook.ToString("yyyy-MM-dd")
Try
Dim sqlQuery As String = "INSERT INTO bookings SET " & _
"Date='" & strDateToBook & "'," & _
"RoomID='" & strComputerRoomToBook & "', " & _
"Length='" & intNewBookingLength & "', " & _
"Period='" & intNewStartPeriod & "', " & _
"UserID='" & intid & "'"
Dim command = New MySqlCommand(sqlQuery, SQLConnection)
command.ExecuteNonQuery
Catch excep As Exception
MsgBox(excep.Message)
End Try
Next
End Using
Also, you may want to change how to pass your values into a parameter. This will prevent SQL Injection.