How to export data from Access to a text file - vb.net

net. My question is how to export data from Access to a text file using vb.net. In my database has Table1 which consists FirstName and LastName so I want this data to be exported to a text file.
I stumble on this code and run it and when compiled it but nothing is export to the text file. Can Someone help my with this?
Dim connetionString As String
Dim cnn As OleDbConnection
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Scripts\db.mdb;"
cnn = New OleDbConnection(connetionString)
cnn.Open()
Dim AccessCommand As New System.Data.OleDb.OleDbCommand("SELECT * INTO [Text;HDR=No;DATABASE=C:\Scripts\TextFiles].[Result.txt] FROM Table1", cnn)
cnn.Close()
Thanks in advance!

This question is downvoted is because you can actually find plenty of example from the website.
Perhaps you do not know what keyword to search?
Try something like "dataset to textbox"?
or something here? Export a C# DataSet to a text file
Updated
I understand you may be new to vb. I will not give you the exact code but tell you what you can do.
First, declare a dataTable/dataset (I would prefer DataTable) to hold your query result from DB.
Dim dtresult As DataTable = 'Result from DB
Then loop through the datatable rows and get the data append into a string builder(or any other way you like to build your string)
Then append the string into the txt file.
This is something you can do.
UPDATE 2
Okay, something like this.
Private Sub DataTableToTXT()
Dim connetionString As String
Dim cnn As OleDbConnection
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Scripts\db.mdb;"
cnn = New OleDbConnection(connetionString)
Dim dtResult As New DataTable
cnn.Open()
'Change the query
Dim dataAdap As New OleDbDataAdapter("SELECT * FROM TABLE1", cnn)
dataAdap.Fill(dtResult)
cnn.Close()
'Change the path to your desired path
Dim exportPath As String = "C:\Export\"
Dim exportFileName As String = "data.txt"
If Not Directory.Exists(exportPath) Then
Directory.CreateDirectory(exportPath)
End If
Dim writer As New StreamWriter(exportPath + exportFileName)
Try
Dim sb As New StringBuilder
For Each row As DataRow In dtResult.Rows
sb = New StringBuilder
For Each col As DataColumn In dtResult.Columns
sb.Append(row(col.ColumnName))
Next
writer.WriteLine(sb.ToString())
Next
Catch ex As Exception
Throw ex
Finally
If Not writer Is Nothing Then writer.Close()
End Try
End Sub

Related

Error while inserting image into access database

I am trying to insert an image into my MS Access 2007 database. The datatype I chose is "OLEObject" and Fieldname as "Image".
I tried the following code which executes when a button is pressed:
Private Sub ButtonPress()
Dim cmd As New OleDbCommand
Dim MemStream As New IO.MemoryStream
Dim DataPic_Update As Byte()
Dim strImage As String
If Not IsNothing(PictureBox1.Image) Then
PictureBox1.Image.Save(MemStream, Imaging.ImageFormat.Png)
DataPic_Update = MemStream.GetBuffer
MemStream.Read(DataPic_Update, 0, MemStream.Length)
strImage = "?"
MemStream.Close()
Else
DataPic_Update = Nothing
strImage = "NULL"
End If
con.Open()
cmd.CommandText = "INSERT INTO Inventory([Image])" + "VALUES(#Image)"
cmd.Parameters.Add("#Image", OleDbType.Binary).Value = DataPic_Update
cmd.Connection = con
cmd.ExecuteNonQuery()
con.Close()
End Sub
While executing the command "ExecuteNonQuery", I am getting following Error:
"Data type mismatch in criteria expression."
I am not able to solve this error. Can someone please help me with any suggestions or modifications required in my existing code?
I want to insert the image and then retrieve from the access database.
There is no need to concatenate the cmd.CommandText, there is a space missing between "([Image])" and "VALUES(#Image)" so the resulting query is:
"INSERT INTO Inventory([Image])VALUES(#Image)"
Instead of
"INSERT INTO Inventory([Image]) VALUES(#Image)"
There is no need for the brackets surrounding "Image" as the field does not contain a space nor is a reserved keyword.
Check that you have all the dependencies needed to embed binary files in access. This dependencies are sometimes not very clear, per instance I remember that in Windows XP with Access XP you needed to install Paintbrush to be able to acomplish this.
I will recommend you to use the below code which I test on Access Database:
Private Function ReadFile(sPath As String) As Byte()
'Initialize byte array with a null value initially.
Dim data As Byte() = Nothing
'Use FileInfo object to get file size.
Dim fInfo As New FileInfo(sPath)
Dim numBytes As Long = fInfo.Length
'Open FileStream to read file
Dim fStream As New FileStream(sPath, FileMode.Open, FileAccess.Read)
'Use BinaryReader to read file stream into byte array.
Dim br As New BinaryReader(fStream)
'When you use BinaryReader, you need to supply number of bytes to read from file.
'In this case we want to read entire file. So supplying total number of bytes.
data = br.ReadBytes(CInt(numBytes))
fStream.Close()
fStream.Dispose()
Return data
End Function
And code to Save Image to MS Access Database
Dim logo() As Byte = ReadFile("E:\logo.jpg")
' Update(23373, logo)
Try
Dim CN As New OleDbConnection(Str_Conn)
CN.Open()
Dim cmd As New OleDbCommand("Update TblInventory Set Image=#img Where Image_ID=#id", CN)
cmd.Connection = CN
cmd.Parameters.Add(New OleDbParameter("#finger", DirectCast(logo, Object)))
cmd.Parameters.AddWithValue("#id", 51384)
cmd.ExecuteNonQuery()
CN.Close()
Catch ex As Exception
MessageBox.Show("Error Occured while Registering Finger Prints, Try Again" + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
End Try
Important Note: You must pass parameters in the Same Sequence you mentioned in Query.

I get only column headers using sqldatareader and datagridview

I have a SQL Server 2008 express with a database and a table and using VB 2010 express.
I am trying to read from that table with sqldatareader, but I only one row in the datagridview with the column headers, no row with data.
What am I doing wrong? (I'm a newbe).
The connection string is :
Data Source=xxxxxxxxxx\SQLEXPRESS;Initial Catalog=Masteca_Inventory;Integrated Security=True
Dim searchStr As String = ""
Dim connetionString As String
Dim sqlCnn As SqlConnection
Dim sqlCmd As SqlCommand
Dim sqlStr As String
Public bindingSource1 As New BindingSource()
connetionString = My.Settings.SQLconnSTR
sqlStr = "SELECT * FROM Piese WHERE " & searchStr 'searchStr is OK I fill it elsewhere
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
sqlCmd = New SqlCommand(sqlStr, sqlCnn)
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
Using sqlReader
Dim dTable As New DataTable
dTable.Load(sqlReader)
bindingSource1.DataSource = dTable
End Using
SearchReport.DataGridView1.DataSource = bindingSource1
'SearchReport is another form
sqlReader.Close()
sqlCmd.Dispose()
sqlCnn.Close()
SearchReport.Show()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
You are not reading the data as a group (you are fetching only one result).
You will need to adjust the code to use a While sqlReader.Read;
Example;
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
While sqlReader.Read()
Try
'Do the work needed
rowResult += sqlReader(0) 'This will contain the result script
Catch ex As Exception
'Catch exception
End Try
End While
Something like that should work (I have not tested the code but the concept is the same).
PS - I strongly suggest you adjust your script to add a Where clause and / or the columns needed (Select * is not a "good practice")
Hope this helps.

SQLXML Import/Export

I have a SQL DB from which I export data as XML using VB.Net code. The code is relatively simple, works quickly, and formats the XML beautifully. The code is:
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim ds As New DataSet
Dim sql As String
connetionString = "**connectionstring**"
connection = New SqlConnection(connetionString)
sql = "select * from costdata"
Try
connection.Open()
adapter = New SqlDataAdapter(sql, connection)
adapter.Fill(ds)
connection.Close()
ds.WriteXml("**PATH**")
MsgBox("Done")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
The problem I'm having is loading this data back in. It seems like it should be as easy as the above, but I can't seem to get a simple way to do it.
It's my understanding that I can use an XMLReader coupled with ADO.NET, but in that case I need to define the columns for the DataTable to insert the XML Data into before I import it all into the DB.
Is there any way to keep from having to hard-code column values in the DataTable, and have the exported XML data import in similar fashion to the above?
Though it's not automated by column name, I decided that hardcoding the mappings wasn't too big a hassle. I'm all ears for an automated way, however. My solution:
Dim connectionString As String = "Data Source=(localdb)\v11.0;Initial Catalog=localACETest;Integrated Security=True"
Try
Using sqlconn As New SqlConnection(connectionString)
Dim ds As New DataSet()
Dim sourcedata As New DataTable()
ds.ReadXml("C:\Users\coopere.COOPERE-PC\Desktop\Test.xml")
sourcedata = ds.Tables(0)
sqlconn.Open()
Using bulkcopy As New SqlBulkCopy(sqlconn)
bulkcopy.DestinationTableName = "ScheduleData"
bulkcopy.ColumnMappings.Add("Id", "Id")
bulkcopy.ColumnMappings.Add("Period", "Period")
...
bulkcopy.WriteToServer(sourcedata)
End Using
sqlconn.Close()
End Using
MsgBox("Done")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Here is a way to automate column mappings ... it assumes the table exists with the same structure in the target database. Cheers :-)
Public Shared Function BulkCopyXML( _
path_ As String, _
connection_string_ As String, _
messages_ As List(Of String), _
exceptions_ As List(Of Exception) _
) As Boolean
Dim result_ As Boolean = False
Try
Dim dataset_ As New DataSet()
dataset_.ReadXml(path_)
Dim datatable_ As DataTable = Nothing
Using connection_ As SqlClient.SqlConnection = New SqlClient.SqlConnection(connection_string_)
connection_.Open()
Using bulkCopy_ As SqlClient.SqlBulkCopy = New SqlClient.SqlBulkCopy(connection_)
For Each datatable_ In dataset_.Tables()
messages_.Add(datatable_.TableName)
bulkCopy_.DestinationTableName = datatable_.TableName
bulkCopy_.ColumnMappings.Clear()
For Each dataColumn_ As DataColumn In datatable_.Columns
bulkCopy_.ColumnMappings.Add(dataColumn_.ColumnName, dataColumn_.ColumnName)
Next
bulkCopy_.WriteToServer(datatable_)
Next
End Using
End Using
result_ = True
Catch exception_ As Exception
If exceptions_ Is Nothing Then
Throw exception_
Else
exceptions_.Add(exception_)
End If
Finally
End Try
Return result_
End Function

operator/operand type mismatch when update dbf file

i have a program needs to update data in dbf file. but it keeps appear error 'operator/operand type mismatch'. here is sample code :
Dim con As OleDbConnection = New OleDbConnection("Provider=vfpoledb;Data Source=C:\folder\paytran.dbf;Collating Sequence=machine;")
Try
Dim strSQL As String = "UPDATE paytran.dbf SET workhr = 20 WHERE empno = 102"
Dim cmd As OleDbCommand = New OleDbCommand(strSQL, con)
con.Open()
Dim myDA As OleDbDataAdapter = New OleDbDataAdapter(cmd)
Dim myDataSet As DataSet = New DataSet()
' Using DataAdapter object fill data from database into DataSet object
myDA.Fill(myDataSet, "MyTable")
' Binding DataSet to DataGridView
DGV.DataSource = myDataSet.Tables("MyTable").DefaultView
con.Close()
con = Nothing
Catch ex As Exception
MessageBox.Show(ex.Message, "Error Select Data")
Finally
If con IsNot Nothing Then
con.Close()
End If
End Try
please help me..
Its your connection string. The connection string should only have to point to the PATH where the data files are located, then all the SQL based commands will by default be able to see any .DBF tables IN that path (or forward if subpaths exists).
Data Source=C:\folder
instead of
Data Source=C:\folder\paytran.dbf
So, now if you have 30 tables in the "C:\folder", you can now query from ALL of them as needed.
You need to explicitly open and close the DBF. Try:
Dim strSQL As String = "Use paytran in 0 shared;UPDATE paytran SET workhr = 20 WHERE empno = 102;use in select('paytran')"

Loop through action

I am new to visual basic, however I need to loop through rows in a data table and use the values to in a test script, the script is as follows -
Public Function TestMain(ByVal args() As Object) As Object
StartApp(URL)
' HTML Browser '
Browser_HtmlBrowser(Document_HomePage(),DEFAULT_FLAGS).Maximize()
Button_AddNewProfilesubmit().Click()
'here is where the rows would be read and the loop would start'
Text_Ctl00MainContentProfileNa().Click(AtPoint(6, 13))
Browser_HtmlBrowser(Document_Http1921685526UserCon(), DEFAULT_FLAGS).InputChars("dataBase_Row_Value")
Table_HtmlTable_1().Click(AtCell( _
AtRow(AtIndex(0)), _
AtColumn(AtIndex(1))))
'here is where the loop would end after all rows had been read'
Return Nothing
End Function
I have an idea to achieve this, first doing a database connection, then create the loop -
Dim pName As String
Dim datas As DataSet
Dim datar As DataRow
Dim oledat As SqlDataAdapter
oledat = New SqlDataAdapter("SELECT COLUMN FROM DATABASE",ConnectionString)
oledat.Fill(datas)
For Each datar In datas.Tables(0).Rows
pName = datar.Item("PROFILENAME")
Text_Ctl00MainContentProfileNa().Click(AtPoint(6, 13))
Browser_HtmlBrowser(Document_Http1921685526UserCon(), DEFAULT_FLAGS).InputChars(pName)
Table_HtmlTable_1().Click(AtCell( _
AtRow(AtIndex(0)), _
AtColumn(AtIndex(1))))
Next
However this is breaking, even though there are no errors in Visual Studio, there is only the warning that datas is used before it is assigned the values. Where am I going wrong?
I believe you must initialize a new dataset before working with it. Example:
Dim ds As DataSet = New DataSet()
Dim connection As OleDb.OleDbConnection
Dim command As OleDb.OleDbCommand
Dim adapter As New OleDb.OleDbDataAdapter
Dim connString As String = "my Connection string stuff;"
connection = New OleDb.OleDbConnection(connString)
Try
'open the connection
If connection.State = ConnectionState.Open Then
Else
connection.Open()
End If
'fill each data table
command = New OleDb.OleDbCommand(selectOne, connection)
adapter.SelectCommand = command
adapter.Fill(ds, "someTableName")
Catch ex As OleDb.OleDbException
'error, do something
Finally
'close everything down
adapter.Dispose()
If (Not command Is Nothing) Then
command.Dispose()
End If
connection.Close()
End Try
This example uses OLEDB but should be comparable to what you are doing. Once you fill it, you should be able to iterate over the tables. But, first, check to make sure you have a dataset created first:
If (ds IsNot Nothing) Then
'do for statement here
End If
If this does not work, let me know.