Directory pointing to self /creating application with a built-in database - database

I made a simple program with a database connection:
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet 'holds table data
Dim da As OleDb.OleDbDataAdapter 'connection to database connectionobject
Dim sql As String
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = C:/JIMMY.mdb"
con.Open()
sql = "select * from TURNING"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "RECORDS")
con.Close()
Now I heard from someone that in order to make an application with a built in database, I should place the file inside the project.
C:\Users\User\documents\visual studio 2010\Projects\myProject\JIMMY.MDB
How do I make the directory dynamic? So, wherever I place the published application, will it work?

You can make it relative to the application, as explained in HOW TO: Determine the Executing Application's Path:
Dim path As String
path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)
dbSource = "Data Source = " + Path.Combine(path, "jimmy.mdb")

Related

Import data from Excel to SQL Server using vb.net

I am importing data from Excel into a SQL Server database using vb.net. In my Excel file, in column bNumber, there are values of different types i.e some are numbers and some are text:
Telenorx
Telenorx
8
97150219924
97150219924
97150219924
97150219924
Easypayx
92
When I select the data from Excel through OleDbCommand, it retrieves numbers correctly but text values as blank.
In Excel, the column's data type is General.
This is my code to retrieve data from Excel.
excelConn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data
Source= " + OpenFileDialog1.FileName + ";Extended Properties=""Excel 12.0
Xml;HDR=Yes""")
Dim oleDbCommand As OleDbCommand = New OleDbCommand("Select bNumber from
[Sheet1$]", excelConn)
excelConn.open()
Dim dataReader = oleDbCommand.ExecuteReader
dataReader.read()
This is not necessarily a solution for your case yet would I did was created a SQL-Server table with bNumber as nvarchar, used SQL-Server Management Studio to export to Excel where I placed the Excel file in the bin\Debug folder of the project. Using the code below all rows returned properly (as we have a string column strings are returned).
The key here is using IMEX=1 in the connection string, Excel can be finicky, this may or may not resolve the issue.
Imports System.Data.OleDb
Public Class Operations
Public Function GetData(ByVal FileName As String) As List(Of String)
Dim valueList As New List(Of String)
Using cn As New OleDbConnection With
{
.ConnectionString = ConnectionString(FileName)
}
Using cmd As OleDbCommand = New OleDbCommand("SELECT bNumber FROM [Table_1$]", cn)
cn.Open()
Dim reader As OleDbDataReader = cmd.ExecuteReader
While reader.Read
valueList.Add(reader.GetString(0))
End While
End Using
End Using
Return valueList
End Function
Public Function ConnectionString(ByVal FileName As String) As String
Dim Builder As New OleDbConnectionStringBuilder
If IO.Path.GetExtension(FileName).ToUpper = ".XLS" Then
Builder.Provider = "Microsoft.Jet.OLEDB.4.0"
Builder.Add("Extended Properties", "Excel 8.0;IMEX=1;HDR=Yes;")
Else
Builder.Provider = "Microsoft.ACE.OLEDB.12.0"
Builder.Add("Extended Properties", "Excel 12.0;IMEX=1;HDR=Yes;")
End If
Builder.DataSource = FileName
Return Builder.ConnectionString
End Function
End Class
Form code
Private Sub Button3_Click(sender As Object, e As EventArgs) _
Handles Button3.Click
Dim ops As New Operations
Dim fileName As String = IO.Path.Combine(
AppDomain.CurrentDomain.BaseDirectory, "Downloaded.xlsx")
Dim valueList As List(Of String) = ops.GetData(fileName)
For Each value As String In valueList
Console.WriteLine(value)
Next
End Sub
Results in the IDE Output window
Table structure
Worksheet
EDIT: The following link points to a MSDN code sample for working with SpreadSheetLight library. Once downloaded, set startup form to StackOverFlow1QuestionMixedTypesForm. Right click on the solution in solution explorer and select "Restore NuGet Packages", now build and run the project. There are two buttons on the form, first does mixed types for Sheet1 while button two is a variant of the same data laid out differently in Sheet2.
Code sample https://code.msdn.microsoft.com/Alternate-methods-to-work-4c52c4a2

Display data from SQL server to listvew

i'm geek in vb.net, I already make vb.net from application with ms access data base. now i need to use this application for multi user and i want to use SQL server, i use this code to show data from access data base to listview :
con.ConnectionString = "provider=microsoft.ace.oledb.12.0; data source = |datadirectory|\noorapp.accdb;"
con.Open()
Dim dt As New DataTable
Dim ds As New DataSet
ds.Tables.Add(dt)
Dim da As New OleDbDataAdapter("select * from " & Year(Now) & " where cmonth='" & m & "' order by cdate DESC", con)
da.Fill(dt)
Dim myrow As DataRow
For Each myrow In dt.Rows
ListView1.Items.Add(myrow.Item(0)).ToString()
ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(myrow.Item(2))
ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(myrow.Item(3))
ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(myrow.Item(4))
ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(myrow.Item(5))
ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(myrow.Item(6))
ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(myrow.Item(7))
Next
any solution to how make this work for sql server also?
thanks.
change your connection string see here. Also change your OleDbConnection object to SQLConnection and your OleDbDataAdapter to SQLDataAdapter
Your database must already exist in the SQL Server for this to work

Inserting contents of CSV file into database loses 1 record

I have an application that imports a CSV file (no header row) and writes the contents into a datatable. The datatable is then passed on as a parameter to a function in my DAL that uses the sqlBulkCopy command to write the data to a SQL Server database.
I have run tested the code as both a Webforms and Windows Forms environment and noticed that in both cases the first row of data is lost. Does anyone know why this should be the case and how I can rectify it? Thanks for any help.
I should add that this doesn't happen if the CSV file has a header row.
UI
Dim csvFileFolder As String = "D:\PROJECTS\Letters(DOTNET)\TextFiles\"
Dim csvFileName As String = "quad1a.txt"
Dim connString As String = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" _
& csvFileFolder & ";Extended Properties=""Text;HDR=No;FMT=Delimited"""
Dim conn As New Odbc.OdbcConnection(connString)
'Open a data adapter, specifying the file name to load
Dim da As New Odbc.OdbcDataAdapter("SELECT * FROM [" & csvFileName & "]", conn)
'Then fill a data table, which can be bound to a grid
Dim dt As New DataTable
da.Fill(dt)
grdQuad.DataSource = dt
grdQuad.DataBind()
LettersBLL.TemporaryPatientManager.InsertIntoBulkTable(dt)
DAL
Public Shared Function InsertIntoBulkTable(dt As DataTable) As DataTable
Using myConnection As New SqlConnection(ApplicationConfiguration.ConnectionString)
Using sqlBulkCopy As New SqlBulkCopy(myConnection)
'Set the database table name
sqlBulkCopy.DestinationTableName = "tblBulkInsert"
myConnection.Open()
sqlBulkCopy.WriteToServer(dt)
myConnection.Close()
End Using
End Using
Return Nothing
End Function
Try this...
Dim connString As String = "Driver={Microsoft Text Driver (*.txt; *.csv)};HDR=No;Dbq=" _& csvFileFolder & ";Extended Properties=""Text;HDR=No;FMT=Delimited"""
Added 'HDR=No' to your connection string
Or try specifying your sqlbulkcopy column mappings.
msdn.....
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.columnmappings.aspx
Example.....
http://www.codeproject.com/Articles/18418/Transferring-Data-Using-SqlBulkCopy

Using SqlBulkCopy with 2 Different Connection Strings

I have an application that gets information from one server (server config stuff) and puts it into a centralized database on another server. There are several servers that I loop over from a text file. I'm writing this application to eliminate the need for linked servers.
I'm trying to use SqlBulkCopy for copying the data but I'm running into problems. I have been successful using SqlBulkCopy with a single SQL connection but when I try to use 2 different SQL connections I run into problems. The data never reaches its destination database. I have debugged through the code and can see that it reaches the try/catch but it appears that the command bulkcopy.WriteToServer(reader) it doesn't actually write any data to SQL.
Dim connectionString As String = "Server= <ThatServer>; integrated security=true"
Dim connectionString2 As String = "Server= <MyServer>; Initial Catalog = <CentralizedDatabase>; integrated security=true"
Using sourceConnection As SqlConnection = _
New SqlConnection(connectionString)
sourceConnection.Open()
Dim commandSourceData As SqlCommand = New SqlCommand("<mySQLcommand>", sourceConnection)
Dim reader As SqlDataReader = commandSourceData.ExecuteReader
Using sourceConnection2 As SqlConnection = _
New SqlConnection(connectionString2)
sourceConnection2.Open()
Using destinationConnection As SqlConnection = _
New SqlConnection(connectionString2)
Using bulkcopy As SqlBulkCopy = _
New SqlBulkCopy(destinationConnection)
bulkcopy.DestinationTableName = _
"<MyTableName>"
Try
bulkcopy.WriteToServer(reader)
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
reader.Close()
End Try
End Using
End Using
sourceConnection2.Close()
End Using
sourceConnection.Close()
End Using
Can anyone see what I'm doing wrong? Thanks in advance!
**Solved. Here's my code that works:
Dim connectionString As String = "Server = <ThatServer>; Initial Catalog = <sourceDB>; integrated security = true"
Dim connectionString2 As String = "Server= <MyServer>; Initial Catalog = <destinationDB>; integrated security=true"
Using sourceConnection As SqlConnection = _
New SqlConnection(connectionString)
Dim commandSourceData As SqlCommand = New SqlCommand(<TSQL>, sourceConnection)
sourceConnection.Open()
Dim reader As SqlDataReader = commandSourceData.ExecuteReader()
Using destinationConnection As SqlConnection = _
New SqlConnection(connectionString2)
destinationConnection.Open()
Using bulkCopy As SqlBulkCopy = _
New SqlBulkCopy(destinationConnection)
bulkCopy.ColumnMappings.Add("SourceColumn1", "DestinationColumn1")
bulkCopy.ColumnMappings.Add("SourceColumn2", "DestinationColumn2")
bulkCopy.ColumnMappings.Add("SourceColumn3", "DestinationColumn3")
bulkCopy.ColumnMappings.Add("SourceColumn4", "DestinationColumn4")
bulkCopy.ColumnMappings.Add("SourceColumn5", "DestinationColumn5")
bulkCopy.ColumnMappings.Add("SourceColumn6", "DestinationColumn6")
bulkCopy.ColumnMappings.Add("SourceColumn7", "DestinationColumn7")
bulkCopy.DestinationTableName = "<destinationTable>"
bulkCopy.WriteToServer(reader)
End Using
destinationConnection.Close()
End Using
reader.Close()
sourceConnection.Close()
End Using

vb write information from SQL Server database

I use visual basic 2008 and a SQL Server database. I want to write the information stock in the database and I want to be rank like in php I use table to rank information what the method to do that in vb. This code write only last information into the table tbl_cars
Dim da As SqlDataAdapter
Dim dt As DataTable
Dim sqlconn As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\m7md\Documents\Visual Studio 2008\Projects\Cars\Cars\cars.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True")
dt = New DataTable
da = New SqlDataAdapter
Dim sql As String = ("select * from tbl_cars ")
da = New SqlDataAdapter(sql, sqlconn)
sqlconn.Open()
da.Fill(dt)
For Each drRow As DataRow In dt.Rows
Label6.Text= (drRow.Item("db_type").ToString)
Label7.Text = (drRow.Item("db_gender").ToString)
Label8.Text = (drRow.Item("db_color").ToString)
Label9.Text = (drRow.Item("db_price").ToString)
Next
End Sub

Resources