SQLBulkCopy does not work - vb.net

This is my first attempt to use sqlbulkcopy class. When I run it, nothing happens, no errors whatsoever. Please help me.
Here is my code:-
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration.ConfigurationManager
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim connectionString As String = GetConnectionString()
' Open a connection
Using sourceConnection As SqlConnection = New SqlConnection(connectionString)
sourceConnection.Open()
' Perform an initial count on the destination table.
Dim commandRowCount As New SqlCommand("SELECT COUNT(*) FROM dbo.BRANCH;", sourceConnection)
Dim countStart As Long = System.Convert.ToInt32(commandRowCount.ExecuteScalar())
Console.WriteLine("Starting row count = {0}", countStart)
' Get data from the source table as a SqlDataReader.
Dim commandSourceData As SqlCommand = New SqlCommand("select * from BRANCH", sourceConnection)
Dim reader As SqlDataReader = commandSourceData.ExecuteReader
UpdateHQDB(reader)
End Using
End Sub
Private Function GetConnectionString() As String
Return "Data Source=127.0.0.1;Initial Catalog=SOURCEDB;User ID=sa;Password="
End Function
Private Function GetDestString() As String
Return "Data Source=192.168.123.194;Initial Catalog=DESTINATIONDB;User ID=sa;Password="
End Function
Public Sub UpdateHQDB(ByVal reader)
Dim DestConString As String = GetDestString()
' Open a connection
Using DestinationConnection As SqlConnection = New SqlConnection(DestConString)
DestinationConnection.Open()
' Perform an initial count on the destination table.
Dim DestcommandRowCount As New SqlCommand("SELECT COUNT(*) FROM dbo.BRANCH;", DestinationConnection)
Dim DestcountStart As Long = System.Convert.ToInt32(DestcommandRowCount.ExecuteScalar())
Console.WriteLine("Starting row count at destination = {0}", DestcountStart)
Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(DestinationConnection)
bulkCopy.DestinationTableName = "dbo.BRANCH"
Try
' Write from the source to the destination.
bulkCopy.WriteToServer(reader)
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
' Close the SqlDataReader. The SqlBulkCopy
' object is automatically closed at the end
' of the Using block.
reader.Close()
End Try
End Using
' Perform a final count on the destination table
' to see how many rows were added.
Dim countEnd As Long = _
System.Convert.ToInt32(DestcommandRowCount.ExecuteScalar())
Console.WriteLine("Ending row count = {0}", countEnd)
Console.WriteLine("{0} rows were added.", countEnd - DestcountStart)
Console.WriteLine("Press Enter to finish.")
Console.ReadLine()
End Using
End Sub
End Class

i would say that use NotifyAfter and SqlRowsCopied event of SqlBulkCopy to troubleshoot
following code in c#
sb.NotifyAfter = 1;
sb.SqlRowsCopied += new SqlRowsCopiedEventHandler(sb_SqlRowsCopied);
void sb_SqlRowsCopied(object sender, SqlRowsCopiedEventArgs e)
{
// See if this event fired
}

Related

How do i get the data to my database using vb.net (class, module and form)

I hope the title is enough to understand my problem, I already installed whats need to run the ADO.NET, I already have a connection string in my module and data query in my class,
Imports System.Data
Imports System.Data.OleDb
Module GlobalVariables
Public sGlobalConnectionString As String
Friend conString As String
Public dr As OleDbDataReader
Sub Main()
Dim sGlobalConnectionString As New OleDb.OleDbConnection
Dim sDataserver As String
Dim sDatabaseName As String
Dim sDatabaseConnection As String
sDataserver = "localhost"
sDatabaseName = "employee"
sDatabaseConnection = "Driver={MariaDB ODBC 3.1 Driver}; SERVER=" & sDataserver & "; UID=root;PWD=******; Database=" & sDatabaseName & "; PORT=3307; OPTION=3"
sGlobalConnectionString = New OleDb.OleDbConnection(conString)
End Sub
End Module
this is my class
Imports System.Data.OleDb
Public Class clsDataQuery
Public Shared Sub Class_initialize()
Dim con = New OleDb.OleDbConnection
con.ConnectionString = sGlobalConnectionString
con.Open()
End Sub
Public Shared Sub Class_Terminate()
Dim con = New OleDb.OleDbConnection
If Not con Is Nothing Then
con.Close()
con = Nothing
End If
End Sub
Public Function GetRecordDataSet(ByVal sStoreProcName As String, ByVal sParameterList As String)
Dim cmd As New OleDbCommand()
Dim arrParameter, arrParamName
Dim sParamName As String
Dim sDataValue
Dim lCtr As Long
On Error GoTo errhandler
cmd.Connection = New OleDb.OleDbConnection
cmd.CommandTimeout = 1800
cmd.CommandText = CommandType.Text
If Not Trim(sParameterList) = "" Then
arrParameter = Split(sParameterList, "|", , vbTextCompare)
If UBound(arrParameter) >= 0 And IsArray(arrParameter) Then
For lCtr = 0 To UBound(arrParameter)
arrParamName = Split(arrParameter(lCtr), "$", , vbTextCompare)
sParamName = arrParamName(0)
sDataValue = arrParamName(1)
cmd.Parameters.Item(sParamName) = sDataValue
Next lCtr
End If
End If
GetRecordDataSet = cmd.ExecuteReader
cmd = Nothing
Exit Function
errhandler:
MessageBox.Show("Records Not Found!!!")
End Function
End Class
if this button is click, the value of Textbox1.text will search in the database if it is exist, if exist it will continue into another form if not error message will appear, how do i do that?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim username = txtbox_lastname.Text
If username <> "" Then
Try
clsDataQuery.Class_initialize()
Catch ex As Exception
MessageBox.Show("No Record Found")
End Try
Else
MessageBox.Show("No Record Found!!!")
End If
End Sub
If this is MariaDb then you want to use the provider for MySql. Not ODBC and not OleDb. No wonder you are having problems. There is not much information available for this database compared to the usual Access database used for beginners.
Do not declare database objects anywhere but the method they are used in. You can declare a Private variable for the connection string at the class level.
Although one of these is a Module level variable and one is a local variable, it is very confusing and bad practice. Why would you call a connection object a String?
Public sGlobalConnectionString As String
Dim sGlobalConnectionString As New OleDb.OleDbConnection
BTW, it is fine to declare and initialize your variables in a single line.
Dim sDataserver = "localhost"
You create a new connection on the first line of Sub Main, then you throw it away and create another new connection on the last line. Since sDataServer and sDatabaseName are hard coded why not just put the literal values directly into the connection string.
After all that you pass conStr to the constructor of the connection instead of sDatabaseConnection. Why were you building sDatabaseConnection (another misnomer, it is not a connection, its a string) and then never use it. Has conStr been set elsewhere?
At any rate, throw out the whole module.
Moving on to your DataQuery class. First, the name should begin with an upper case letter.
Get rid of Class_initialize. We don't want to create or open any connection except in the method where it is used. You never call Class_Terminate so dump that too.
The GetRecordDataSet method...
Functions in vb.net require a datatype. The old VB6 syntax of assigning the return value to the name of the function will work but it is not the .net way. In vb.net we use the Return keyword.
You have not initialized or given a datatype to arrParameter, arrParamName or sDataValue which violates Option Strict. (You do have Option Strict On, don't you?)
On Error GoTo errhandler is a sad leftover from VB6. .net languages have structured error handling with Try...Catch...Finally...End Try.
cmd.Connection = New OleDb.OleDbConnection sets the connection property however this new connection has no connection string.
cmd.CommandText = CommandType.Text Now this is just silly. What I think you want is cmd.CommandType =CommandType.StoredProcedure
Using...End Using blocks take care of declaring, closing and disposing database objects even if there is an error. You don't want to return a DataReader because a reader requires an open connection. cmd.ExecuteReader returns a DataReader. I used the reader to load a DataTable and returned the DataTable.
It seems you are trying to develop a factory pattern but it is way too advanced for your. Just pass value and call a method specific to what your are searching for. You want your DataQuery code to be independent from your user interface. The Button code doesn't care where the data is coming from. It could be a database, a text file, or a web service. Likewise the DataQuery code doesn't know where the values are coming from. It could be a WinForms app, a web application or a phone app.
Public Class DataQuery
Private Shared ConStr As String = "server=localhost;userid=root;database=employee"
Public Shared Function SearchByLastName(ByVal LName As String) As DataTable
Dim dt As New DataTable
Using cn As New MySqlConnection(ConStr),
cmd As New MySqlCommand("Select * From PutTableNameHere Where LastName = #LName", cn)
cmd.Parameters.Add("#LName", MySqlDbType.VarChar).Value = LName
cn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
End Class
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim dt As DataTable = Nothing
If txtbox_lastname.Text <> "" Then
Try
dt = DataQuery.SearchByLastName(txtbox_lastname.Text)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End If
DataGridView1.DataSource = dt
End Sub
Before answering, I really think that the GetRecordDataSet() at the very least a darn good tidy up, better yet removed from history
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim username = txtbox_lastname.Text
If username <> "" Then
Try
clsDataQuery.Class_initialize()
Dim reader = GetRecordDataSet("storedProcName", txtbox_lastName.Text)
Do While reader.Read()
'Process record etc
Loop
Catch ex As Exception
MessageBox.Show("No Record Found")
End Try
Else
MessageBox.Show("No Record Found!!!")
End If
End Sub
Might be a bit rough, but should get you heading in the right direction

Cant Load data Mysql and show error "is not alowed to connect host" in VB

net
i try to create a class for CRUD and i have error
for display data to gridview
this is my class for connection and run query
Imports MySql.Data.MySqlClient
Public Class klass_koneksi
Public sqlconn As New MySqlConnection
Public query As String
Public query_table As String
Public v_grid As New DataGridView
Public sqlcmd As New MySqlCommand
Public sqladpt As New MySqlDataAdapter
Public sqltabel As New DataTable
Public Function open_db()
sqlconn.ConnectionString = "server=127.0.0.1;username=root;pwd=;database=inventor_brg"
sqlconn.Open()
End Function
Public Function Run_Query(query)
Try
sqlcmd = sqlconn.CreateCommand
sqlcmd.CommandText = query
sqlcmd.ExecuteNonQuery()
Catch ex As Exception
End Try
End Function
Public Function open_table(query_table, v_grid)
Try
sqlcmd.Connection = New MySqlConnection
sqlcmd.CommandText = query_table
sqladpt.SelectCommand = sqlcmd
sqladpt.Fill(sqltabel)
v_grid = sqltabel
Catch ex As MySqlException
MsgBox("cant connect :" & ex.Message)
End Try
End Function
Public Function close_db()
sqlconn.Close()
sqlconn.Dispose()
End Function
End Class
and load data code
Sub load_data()
Dim sql_select As New klass_koneksi
Dim query As String = "Select* from t_barang"
sql_select.open_db()
sql_select.open_table(query, Mgrid.DataSource)
sql_select.close_db()
End Sub
Private Sub frmbrg_Load(sender As Object, e As EventArgs) Handles MyBase.Load
load_data()
End Sub
and this code show error
cant connect:Host'xxxxxxxxxxxxx' is not allowed to connect MariaDB server
is there anything wrong with my class code for load data to grid view?

Object not instantiated?

I get the following error when running this code. I am trying to query data out of my SQL database using parameters and appear to have most everything I need, but I can't quite figure out the error on this one. My debugging attempts have failed:
"Object reference not set to an instance of an object"
Option Strict Off
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Windows.Forms
Imports System.Drawing
Imports System.IO
Public Class Form1
Dim thisConnection = New SqlConnection("Server=myserver;Database=myDatabase;User Id=username;Password=password")
Dim DBCommand As SqlCommand
Dim myReader As SqlDataReader
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
thisConnection.Open()
Console.WriteLine("Connect Open")
DBCommand.Parameters.AddWithValue("#dateOld", "20151215")
DBCommand.Parameters.AddWithValue("#dateNew", "20151231")
Dim myReader = DBCommand.ExecuteReader()
Dim fNextResult As Boolean = True
Dim fileName As String = "C:\Users\Documents\MomInt.txt"
DBCommand = New SqlCommand("*****SQL code*****")
Dim outputStream As StreamWriter = New StreamWriter(fileName)
'Get all values from the current item on the reader as long asRead() returns true...
Do While myReader.Read
'make an array the length of the available fields
Dim values(myReader.FieldCount - 1) As Object
'get all the field values
myReader.GetValues(values)
'write the text version of each value to a comma seperated string
Dim line As String = String.Join(",", values)
'write the csv line to the file
outputStream.WriteLine(line)
Loop
myReader.Close()
outputStream.Close()
Me.Text = "Success!"
Me.BackColor = Color.Chartreuse()
thisConnection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Connection Failed!", MessageBoxButtons.AbortRetryIgnore)
End Try
End Sub
End Class

Parsing textfile to access database in VB.NET

I am trying to store the information from text file into the database. This is what I have but could not figure out what to do next.
Imports System.IO
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim filename As String
filename = Application.StartupPath + "\darsReport.txt"
Dim iofile As New StreamReader(filename)
If File.Exists(filename) Then
Dim ioline As String
Dim ID, studentName, currentGPA, ReqGPA, expectedGraduation
ioline = iofile.ReadLine
While Not ioline = ""
Dim mysplit = Split(ioline, " ")
ID = mysplit(1)
studentName = mysplit(0)
expectedGraduation = mysplit(2)
currentGPA = mysplit(3)
ReqGPA = mysplit(4)
End While
Else
MsgBox(filename + "Does not exist.")
End If
End Sub
End Class
After this you need to run an INSERT query on your database table. The simplest way to do that is to use SqlCommand class (assuming that you have a SQL Server database):
Dim con as new SqlConnection("Your Connection String Here")
con.Open()
Dim cmd as New SqlCommand("", con)
cmd.CommandText = String.Format("INSERT INTO [YourTable](ID, Name, CurrentGPA) VALUES({0}, '{1}', {2})", ID, studentName, currentGPA)
cmd.ExecuteNonQuery()
con.Close()
Use this code block inside your loop and all your rows will be inserted into the database. However note that this is really the very basic way of doing it and a lot more code should be written to properly handle exceptions, invalid data etc. Also this method can easily be exploited using SQL Injections. Far better apporaches exist in .NET (e.g. DataSets and Entity Framework) that should rather be used for this task.

OleDbException was unhandled, syntax error in WHERE clause?

Having trouble with a persistent error. My form allows the user to see a list of elements in a particular group. The input for group number is a combobox called groupbox and the output is a combobox called ElementResults. I am getting the error on the line: GroupSearch.ExecuteNonQuery()
Imports System.Data.OleDb
Public Class ElementsSearch
Public Shared connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents and Settings\A\My Documents\Visual Studio 2010\Projects\A2\Element.accdb;Persist Security Info=False;"
Public Shared ElementsTable
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim Search As New OleDbConnection(connectionString)
Search.Open()
Dim SearchCriteria As String
SearchCriteria = Groupbox.Text
Dim query As String = "SELECT * From ElementsTable WHERE Group='" & SearchCriteria & "'"
Dim GroupSearch As New OleDbCommand(query, Search)
GroupSearch.ExecuteNonQuery()
Dim reader As OleDbDataReader = GroupSearch.ExecuteReader()
ElementResults.Text = Convert.ToString(reader("Name"))
End Sub
End Class
You define the field group which is a reserved keyword.
Try [group] instead like in this sample:
SELECT * From ElementsTable WHERE [Group]='aaa'
To avoid all the errors you're getting, consider changing your code to something like this:
Using connection As New OleDbConnection(connectionString)
connection.Open()
Using command As New OleDbCommand("SELECT * From ElementsTable WHERE [Group]=#Group", connection)
command.Parameters.AddWithValue("#Group", SearchCriteria)
Using reader As OleDbDataReader = command.ExecuteReader()
Do While reader.Read()
ElementResults.Text = reader.GetString("Name")
Loop
End Using
End Using
End Using