Closing OleDbConnection slow - vb.net

I am using this function to upload a excel file in a datatable or datagridview, my problem is that at the beginning the program was executed instantaneously but now wastes a couple of seconds running the command xlsConn.Close (), any idea why now is slower if at the beginning it ran instantly? Also if I eliminate that command (xlsConn.Close ()), I will have any problems? I've seen that I get some problems trying to open the uploaded excel file, it only gives me reading access.
Function ReadExcelFile(ByVal InputFile As String, ByVal DataSheet As String)
InputFile = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & InputFile & ";Extended Properties=Excel 12.0"
DataSheet = "select * from [" & DataSheet & "$]"
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim cmd As New OleDbCommand
Dim xlsConn As OleDbConnection
xlsConn = New OleDbConnection(InputFile)
Try
xlsConn.Open()
cmd.Connection = xlsConn
cmd.CommandType = CommandType.Text
cmd.CommandText = (DataSheet)
da.SelectCommand = cmd
da.Fill(dt)
Catch
MsgBox(ErrorToString)
Finally
xlsConn.Close()
xlsConn = Nothing
End Try
Return dt
End Function

Related

Saving data to access not working, despite no errors

Hey I'm trying to use this code to save to my access database and although there are no errors and it says data saved, my access database doesn't receive the new data. What's wrong with it?
Private Sub savenew()
Dim conn As New OleDbConnection
conn = New OleDbConnection
dbprovider = "Provider=Microsoft.ACE.OLEDB.12.0;"
dbsource = "Data Source = FULL YUGIOH ACCESS DATABASE.accdb;"
conn.ConnectionString = dbprovider & dbsource
Dim reader As OleDbDataReader
Dim command As OleDbCommand
Try
conn.Open()
Dim query As String
query = "insert into item(name) values ('" & TextBox4.Text & "')"
command = New OleDbCommand(query, conn)
reader = command.ExecuteReader
MsgBox("data saved")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
(table in my database is called item, and column is called name.)

Set datasource of datagridview in module

I am writing a program that will automatically process files, based on a set of criteria. In order to process these, I need to load the Excel file first, before I can process it.
I create a module called "NewBusAuto". In here, I created a new datagridview. I am trying to set the datasource of this, but whenever I do, it doesn't actually bind. When I try and process each row/column, it is saying it is still empty.
Code used:
Module m_NewBusinessAutomation
Dim dgvImport As DataGridView
Public Sub NewBusAuto(ByVal folderName As String,
ByVal fileName As String,
ByVal executeScript As String)
dgvImport = New DataGridView
If Path.GetExtension(fileName) = ".xls" Or Path.GetExtension(fileName) = ".xlsx" Then
Using cn As New System.Data.OleDb.OleDbConnection
Dim builder As New OleDbConnectionStringBuilder With _
{.DataSource = folderName & "\" & fileName,
.Provider = "Microsoft.ACE.OLEDB.12.0"}
builder.Add("Extended Properties", "Excel 12.0; IMEX=1;HDR=Yes;")
cn.ConnectionString = builder.ConnectionString
cn.Open()
Using cmd As OleDbCommand = New OleDbCommand With {.Connection = cn}
cmd.CommandText = "SELECT * FROM [Sheet1$]"
Dim dr As System.Data.IDataReader = cmd.ExecuteReader
Dim dt As New DataTable
dt.Load(dr)
dgvImport.DataSource = dt
dgvImport.Refresh()
Messagebox.show(dgvImport.RowCount & "-" & dgvImport.ColumnCount)
dr.Close()
End Using
End Using
End If
The messagebox is giving me "0 - 0" as a result.
I need to load the Excel file to the actual database. Any help would be appreciated!

Can't INSERT INTO access database

I can select the data from an Access database, but I tried many ways to INSERT INTO database. There is no error message, but it didn't insert the data.
Code:
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & CurDir() & "\fsDB1.accdb")
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
conn.Open()
Dim CommandString As String = "INSERT INTO tblfile(stdUname,filePw,filePath,status) VALUES('" & userName & "','" & filePw & "','" & filePath & "','A')"
Dim command As New OleDbCommand(CommandString, conn)
Command.Connection = conn
Command.ExecuteNonQuery()
I just want a simple easy way to INSERT INTO an Access database. Is it possible because of the problem of Access database? I can insert this query by running query directly in Access.
Firstly I would check the database settings. If your app copies a new copy of the database each time you run it that would explain why you can select existing data and why your new data is not being saved (Well it is being saved, but the database keeps getting replaced with the old one). Rather set it up to COPY IF NEWER.
Further, you should ALWAYS use parameterized queries to protect your data. It is also is less error prone than string concatenated commands ans is much easier to debug.
Also, I recommend using a USING block to handle database connections so that your code automatically disposes of resources no longer needed, just in case you forget to dispose of your connection when you are done. Here is an example:
Using con As New OleDbConnection
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; " & _
"Data Source = "
Dim sql_insert As String = "INSERT INTO Tbl (Code) " & _
"VALUES " & _
"(#code);"
Dim sql_insert_entry As New OleDbCommand
con.Open()
With sql_insert_entry
.Parameters.AddWithValue("#code", txtCode.Text)
.CommandText = sql_insert
.Connection = con
.ExecuteNonQuery()
End With
con.Close()
End Using
Here is an example where data operations are in a separate class from form code.
Calling from a form
Dim ops As New Operations1
Dim newIdentifier As Integer = 0
If ops.AddNewRow("O'brien and company", "Jim O'brien", newIdentifier) Then
MessageBox.Show($"New Id for Jim {newIdentifier}")
End If
Back-end class where the new primary key is set for the last argument to AddNewRow which can be used if AddNewRow returns true.
Public Class Operations1
Private Builder As New OleDbConnectionStringBuilder With
{
.Provider = "Microsoft.ACE.OLEDB.12.0",
.DataSource = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Database1.accdb")
}
Public Function AddNewRow(
ByVal CompanyName As String,
ByVal ContactName As String,
ByRef Identfier As Integer) As Boolean
Dim Success As Boolean = True
Dim Affected As Integer = 0
Try
Using cn As New OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Using cmd As New OleDbCommand With {.Connection = cn}
cmd.CommandText = "INSERT INTO Customer (CompanyName,ContactName) VALUES (#CompanyName, #ContactName)"
cmd.Parameters.AddWithValue("#CompanyName", CompanyName)
cmd.Parameters.AddWithValue("#ContactName", ContactName)
cn.Open()
Affected = cmd.ExecuteNonQuery()
If Affected = 1 Then
cmd.CommandText = "Select ##Identity"
Identfier = CInt(cmd.ExecuteScalar)
Success = True
End If
End Using
End Using
Catch ex As Exception
Success = False
End Try
Return Success
End Function
End Class

Save and Read RichText from Access file with Image is SLOW

If I use the following code to write and read rtf data into an access .mdf file its fast to save the data but very slow to read it back.
I tested with a rtf file which is 1mg in size contains around 10 lines in bold and 4 small images.
Is there anyway to read it back faster,
Note if load the rtf from file it takes around 1 sec,
SAVE DATA
Dim constring As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\paul\Documents\Code.mdb"
Using myconnection As New OleDbConnection(constring)
myconnection.Open()
Dim sqlQry As String = "INSERT INTO [table1] ([Code]) VALUES (#Code)"
Using cmd As New OleDbCommand(sqlQry, myconnection)
cmd.Parameters.AddWithValue("#code", RTB1.Rtf)
cmd.ExecuteNonQuery()
End Using
myconnection.Close()
End Using
READ DATA
Dim constring As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\paul\Documents\Code.mdb"
Dim ds As New DataSet
Using myconnection As New OleDbConnection(constring)
myconnection.Open()
Dim strSql As String = "SELECT * FROM table1"
Using cmd As New OleDbCommand(strSql, myconnection)
Dim da As New OleDbDataAdapter(cmd)
da.Fill(ds, "Table")
End Using
myconnection.Close()
End Using
Me.RTB1.rtf = ds.Tables(0).Rows(0).Item(1)

Execute a SQL Stored Procedure and process the results [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
In VB.NET, how do I do the following?
Execute a Stored Procedure
Read through the DataTable returned
At the top of your .vb file:
Imports System.data.sqlclient
Within your code:
'Setup SQL Command
Dim CMD as new sqlCommand("StoredProcedureName")
CMD.parameters("#Parameter1", sqlDBType.Int).value = Param_1_value
Dim connection As New SqlConnection(connectionString)
CMD.Connection = connection
CMD.CommandType = CommandType.StoredProcedure
Dim adapter As New SqlDataAdapter(CMD)
adapter.SelectCommand.CommandTimeout = 300
'Fill the dataset
Dim DS as DataSet
adapter.Fill(ds)
connection.Close()
'Now, read through your data:
For Each DR as DataRow in DS.Tables(0).rows
Msgbox("The value in Column ""ColumnName1"": " & cstr(DR("ColumnName1")))
next
Now that the basics are out of the way,
I highly recommend abstracting the actual SqlCommand Execution out into a function.
Here is a generic function that I use, in some form, on various projects:
''' <summary>Executes a SqlCommand on the Main DB Connection. Usage: Dim ds As DataSet = ExecuteCMD(CMD)</summary>'''
''' <param name="CMD">The command type will be determined based upon whether or not the commandText has a space in it. If it has a space, it is a Text command ("select ... from .."),'''
''' otherwise if there is just one token, it's a stored procedure command</param>''''
Function ExecuteCMD(ByRef CMD As SqlCommand) As DataSet
Dim connectionString As String = ConfigurationManager.ConnectionStrings("main").ConnectionString
Dim ds As New DataSet()
Try
Dim connection As New SqlConnection(connectionString)
CMD.Connection = connection
'Assume that it's a stored procedure command type if there is no space in the command text. Example: "sp_Select_Customer" vs. "select * from Customers"
If CMD.CommandText.Contains(" ") Then
CMD.CommandType = CommandType.Text
Else
CMD.CommandType = CommandType.StoredProcedure
End If
Dim adapter As New SqlDataAdapter(CMD)
adapter.SelectCommand.CommandTimeout = 300
'fill the dataset
adapter.Fill(ds)
connection.Close()
Catch ex As Exception
' The connection failed. Display an error message.
Throw New Exception("Database Error: " & ex.Message)
End Try
Return ds
End Function
Once you have that, your SQL Execution + reading code is very simple:
'----------------------------------------------------------------------'
Dim CMD As New SqlCommand("GetProductName")
CMD.Parameters.Add("#productID", SqlDbType.Int).Value = ProductID
Dim DR As DataRow = ExecuteCMD(CMD).Tables(0).Rows(0)
MsgBox("Product Name: " & cstr(DR(0)))
'----------------------------------------------------------------------'
From MSDN
To execute a stored procedure returning rows programmatically using a command object
Dim sqlConnection1 As New SqlConnection("Your Connection String")
Dim cmd As New SqlCommand
Dim reader As SqlDataReader
cmd.CommandText = "StoredProcedureName"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1
sqlConnection1.Open()
reader = cmd.ExecuteReader()
' Data is accessible through the DataReader object here.
' Use Read method (true/false) to see if reader has records and advance to next record
' You can use a While loop for multiple records (While reader.Read() ... End While)
If reader.Read() Then
someVar = reader(0)
someVar2 = reader(1)
someVar3 = reader("NamedField")
End If
sqlConnection1.Close()
Simplest way? It works. :)
Dim queryString As String = "Stor_Proc_Name " & data1 & "," & data2
Try
Using connection As New SqlConnection(ConnStrg)
connection.Open()
Dim command As New SqlCommand(queryString, connection)
Dim reader As SqlDataReader = command.ExecuteReader()
Dim DTResults As New DataTable
DTResults.Load(reader)
MsgBox(DTResults.Rows(0)(0).ToString)
End Using
Catch ex As Exception
MessageBox.Show("Error while executing .. " & ex.Message, "")
Finally
End Try
Dim sqlConnection1 As New SqlConnection("Your Connection String")
Dim cmd As New SqlCommand
cmd.CommandText = "StoredProcedureName"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1
sqlConnection1.Open()
Dim adapter As System.Data.SqlClient.SqlDataAdapter
Dim dsdetailwk As New DataSet
Try
adapter = New System.Data.SqlClient.SqlDataAdapter
adapter.SelectCommand = cmd
adapter.Fill(dsdetailwk, "delivery")
Catch Err As System.Exception
End Try
sqlConnection1.Close()
datagridview1.DataSource = dsdetailwk.Tables(0)
My Stored Procedure Requires 2 Parameters and I needed my function to return a datatable here is 100% working code
Please make sure that your procedure return some rows
Public Shared Function Get_BillDetails(AccountNumber As String) As DataTable
Try
Connection.Connect()
debug.print("Look up account number " & AccountNumber)
Dim DP As New SqlDataAdapter("EXEC SP_GET_ACCOUNT_PAYABLES_GROUP '" & AccountNumber & "' , '" & 08/28/2013 &"'", connection.Con)
Dim DST As New DataSet
DP.Fill(DST)
Return DST.Tables(0)
Catch ex As Exception
Return Nothing
End Try
End Function