I use following code to set a connection to my database: Return New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\FileRename v5.4.accdb")
I wanted to extent this function by checking if the database exists and If NOT to open a FileOpenDialog to choose another database in another folder. I cant seem to get it to work because when I place the FileOpenDialog on my Main form it throws an Exception error.
Public Function Jokendb() As OleDbConnection
Dim FileName As String = Application.StartupPath & "\FileRename v5.4.accdb"
If IO.File.Exists(FileName) Then
Return New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\FileRename v5.4.accdb")
Else
'Dim result As DialogResult = OpenFileDialog1.ShowDialog()
Dim str As String = OpenFileDialog1.FileName.ToString()
'If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
' Get the file name.
Dim path As String = OpenFileDialog1.FileName
Try
' Read in text.
Dim text As String = File.ReadAllText(path)
Return New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & text)
Catch ex As Exception
' Report an error.
Me.Text = "Error"
End Try
'End If
End If
End Function
I don't know why those line are comented but i think your code could work with these changes:
Public Function Jokendb() As OleDbConnection
Dim FileName As String = Application.StartupPath & "\FileRename v5.4.accdb"
If IO.File.Exists(FileName) Then
Return New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\FileRename v5.4.accdb")
Else
OpenFileDialog1.ShowDialog()
'Dim str As String = OpenFileDialog1.FileName.ToString()
'If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
' Get the file name.
Dim path As String = ""
If OpenFileDialog1.filename <> "" Then
path = OpenFileDialog1.FileName
End If
Try
' Read in text.
Dim text As String = File.ReadAllText(path)
Return New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & text)
Catch ex As Exception
' Report an error.
Me.Text = "Error"
End Try
'End If
End If
End Function
I am trying to import an Excel file into an Access DB via vb.net
the idea is the customer can export the data into excel, modify it, add, delete them importing it back.
The data exported has exactly the same format than the table to import to.
I am using the code below:
Try
Dim strFileName As String = String.Empty
Dim XLda As New OleDbDataAdapter
Dim ExcelTables As New DataTable
Dim StrSelect = "SELECT * FROM [{0}]"
OpenFileDialog1.FileName = ""
OpenFileDialog1.InitialDirectory = mdlGlobalStuff.sMasterDataPath
OpenFileDialog1.Filter = "Excel|*.xls|All files (*.*)|*.*"
If OpenFileDialog1.ShowDialog() <> Windows.Forms.DialogResult.OK Then
Exit Sub
End If
strFileName = OpenFileDialog1.FileName
Dim MyXLConnection As New OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & strFileName & ";Extended Properties=Excel 8.0;")
Using MyXLConnection
Using cmd As New OleDbCommand
cmd.Connection = MyXLConnection
cmd.CommandText = "INSERT INTO [MS Access;Database=InvoicingToolDB.accdb].[tbl_Bases] SELECT * FROM [Sheet1$]"
If MyXLConnection.State = ConnectionState.Open Then
MyXLConnection.Close()
End If
MyXLConnection.Open()
cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
MsgBox("ImportLinkLabel_LinkClicked: Importing Base data" & vbCrLf & ErrorToString())
End Try
I always have an error message saying:
Unrecognized database format 'c:\--path to db--\InvoicingToolDB.accdb'
The path is correct and I don't understand why the format wouldn't be recognized.
Ok I have found the issue. The OLEDB Provider version was not the right one (4.0 is not reading Access .accdb format but old .mdb format only)
Replacing:
Dim MyXLConnection As New OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & strFileName & ";Extended Properties=Excel 8.0;")
With:
Dim MyXLConnection As New leDbConnection("provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & strFileName & ";Extended Properties=Excel 8.0;")
Works perfectly.
At my company we have an initiative that allows users to submit "Winning Ideas". There is a form to fill out, and the user can upload documents on the form. The ideas are voted on by other employees, reviewed by a committee, and the user has the ability to win cash prizes and have their idea implemented in the company.
I created a custom webpart using ASP.NET that allows users to insert a row into a SQL table, and add documents to a SharePoint document list. The list of documents they upload is added to a field in the SQL table, and displayed as hyperlinks on the .aspx page.
Here are some of the issues I have seen with the document upload:
- Document is not uploaded at all.
- Document is uploaded, but not checked in.
- Document is uploaded and checked in, but not linked to a record (the field did not update in SQL).
- If adding multiple documents, both documents are uploaded but the content of the first document is repeated for all documents.
- Multiple entries are created with the Insert statement.
I can't figure out if this is a problem with my SQL or my VB. Is there a better way I should be doing this? Any help would be appreciated.
My current environment is as such:
- SharePoint 2013
- SQL Server 2012
- Microsoft Visual Studio Professional 2013
Partial Public Class WinningIdeasFormUserControl
Inherits UserControl
Public conn As SqlConnection
Public strDatabase As String
Public MyUserInfo As SPUser
Public strFiles As String
Public IdeaId As String
Public uploads As HttpFileCollection
Private Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
'reference to file collection that was sent by the browser request'
uploads = HttpContext.Current.Request.Files
Try
conn = New SqlConnection(strDatabase)
Dim cmd As SqlCommand = New SqlCommand()
strFiles = ""
'SQL command to insert results into the database'
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = "INSERT INTO [WinningIdeas] (Title, Idea, Submitter, SPUserID) OUTPUT INSERTED.ID VALUES (#Title, #Idea, #Submitter, '" & MyUserInfo.ID & "')"
cmd.Parameters.AddWithValue("#Title", txtTitle.Text)
cmd.Parameters.AddWithValue("#Idea", txtIdea.InnerText)
cmd.Parameters.AddWithValue("#Submitter", MyUserInfo.Name)
'confirms that the database has been updated'
cmd.Connection.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
reader.Read()
'set IdeaId to the output of the record that was just added (ID it was assigned in database)'
IdeaId = reader(0).ToString
cmd.Connection.Close()
cmd.Connection = Nothing
If uploads.Count > 1 Then
Try
'if the user uploaded documents, make sure we add them'
uploadDocuments()
Catch ex As Exception
Span1.InnerHtml = "An error has occurred while trying to upload your document(s). Please contact WinnDESK#winnco.com for more information. " & ex.Message & "."
End Try
ElseIf (reader.RecordsAffected = 1) Then 'if a record has been successfully created'
SendEmail()
Response.Redirect("/Pages/Submitted.aspx?IdeaId=" & IdeaId)
End If
Catch ex As Exception
'change the <span> to show the error message'
Span1.InnerHtml = ex.Message
End Try
End Sub
Public Sub uploadDocuments()
'upload files'
For i As Integer = 0 To (uploads.Count - 1)
Dim fileSize As Int64
fileSize = uploads(i).ContentLength
'get the file name from whichever file we are currently saving'
Dim filName As String = System.IO.Path.GetFileName(uploads(i).FileName)
'TODO: Size exception is bringing the user to an exception page. catch as my exception'
'make sure there are no empty files, make sure file is less than 50MB'
If (fileSize > 0 And fileSize < 52428800) Then
Dim spfile As SPFile = SPContext.Current.Web.Files.Add("/Documents/User%20Uploads/" + IdeaId + "_" + filName, FileField.PostedFile.InputStream)
spfile.CheckIn("Checked in by " & MyUserInfo.Name & " for Idea " & IdeaId, SPCheckinType.MajorCheckIn)
spfile.Publish("Published by " & MyUserInfo.Name & " for Idea " & IdeaId)
'separate files with a ";" in the database'
strFiles = strFiles + IdeaId + "_" + filName + ";"
Else
Throw New Exception("Your file, " & filName & ", was not uploaded correctly due to its size.")
End If
Next
Try
conn = New SqlConnection(strDatabase)
Dim cmd As SqlCommand = New SqlCommand()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = "UPDATE WinningIdeas SET Documents = #Documents WHERE ID = " & IdeaId
cmd.Parameters.AddWithValue("#Documents", strFiles)
cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd.Connection.Close()
cmd.Connection = Nothing
Response.Redirect("/Pages/Submitted.aspx?IdeaId=" & IdeaId)
Catch ex As Exception
'change the <span> to show the error message'
Span1.InnerHtml = ex.Message
End Try
End Sub
I've read all the articles and posts from other users on this subject and I'm still stuck.
Essentially what I have is a VB.net program with a local SQL backend. I created a table called "consolDump" that I wish to import an Excel sheet into. I feel like I'm very close just from the help I've gotten from the other people with a similar problem. Just to clarify, I do not have the ability to add software to the machine I'm using (it's heavily restricted by IT), and do not have access to the SQL server import utility.
Here's the code I have. Any help would be appreciated.
Imports System.Data.SqlClient
Public Class formImport
Private Sub buttonConsolImport_Click(sender As Object, e As EventArgs) Handles buttonConsolImport.Click
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim DtSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
Dim fBrowse As New OpenFileDialog
Dim fname As String
Try
With fBrowse
.Filter = "Excel files(*.xls)|*.xls|All files (*.*)|*.*"
.FilterIndex = 1
.Title = "Import data from Excel file"
End With
If fBrowse.ShowDialog() = Windows.Forms.DialogResult.OK Then
fname = fBrowse.FileName
MyConnection = New System.Data.OleDb.OleDbConnection _
("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & fname & ";" & "Extended Properties=""Excel 8.0;HDR=NO;IMEX=1""")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("A1, B1, C1, D1, E1, F1, G1, H1, I1, J1, k1, L1 from [consol_data$]", MyConnection)
MyCommand.TableMappings.Add("Table", "consolDump")
DtSet = New System.Data.DataSet
MyCommand.Fill(DtSet)
For Each Drr As DataRow In DtSet.Tables(0).Rows
Execute_Local("INSERT INTO consolDump(PO_Number, Consol_ID, Status, Contractor, UTAS_Owner, Description, Start_Date, End_Date, Total_Spend, ) VALUES ('" & Drr(0).ToString & "','" & Drr(1).ToString & "','" & Drr(2).ToString & "'),'" & Drr(3).ToString & "','" & Drr(4).ToString & "','" & Drr(5).ToString & "','" & Drr(6).ToString & "','" & Drr(7).ToString & "','" & Drr(8).ToString & "','" & Drr(9).ToString & "','" & Drr(10).ToString & "','" & Drr(11).ToString & "'")
Next
MsgBox("Success")
MyConnection.Close()
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
Ok so, to add to what I've asked, I'm trying to import a csv file from the excel sheet with this code, which works fine.
'Converts consol data to csv file===========================
Dim excelApplication As New Excel.Application
Dim excelWrkBook As Excel.Workbook
excelApplication.Visible = False
excelApplication.DisplayAlerts = False
excelWrkBook = excelApplication.Workbooks.Open("R:\PECOE-WLOX\QuEST\Torres\sqlProjects\consol_data.xls")
excelWrkBook.SaveAs(Filename:="R:\PECOE-WLOX\QuEST\Torres\sqlProjects\consol_data.csv", FileFormat:=Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV)
excelWrkBook.Close()
excelApplication.DisplayAlerts = True
excelApplication.Quit()
MessageBox.Show("Converted to CSV")
'============================================================
Now I'm trying to import the csv file into a new data table but I'm getting a strange error that says "system.data.sql is a namespace and cannot be used as an expression". Now this is probably my inexperience as I pulled the code from another site and several said they have it working. I've modified it to fit my data. Any help would be appreciated. The error appears as a syntax error on "Dim cmd As New SqlClient.SqlCommand(Sql, connection)". It's highlighting the Sql in the paranthesis as a namespace.
Dim consolDump1 As New DataTable()
consolDump1.Columns.Add("PO_Number")
consolDump1.Columns.Add("Consol_ID")
consolDump1.Columns.Add("Status")
consolDump1.Columns.Add("Contractor")
consolDump1.Columns.Add("UTAS_Owner")
consolDump1.Columns.Add("Description")
consolDump1.Columns.Add("Start_Date")
consolDump1.Columns.Add("End_Date")
consolDump1.Columns.Add("Total_Spend")
consolDump1.Columns.Add("Job_Title")
consolDump1.Columns.Add("Location")
consolDump1.Columns.Add("Type")
Dim parser As New FileIO.TextFieldParser("R:\PECOE-WLOX\QuEST\Torres\sqlProjects\consol_data.csv")
parser.Delimiters = New String() {","} ' fields are separated by comma
parser.HasFieldsEnclosedInQuotes = True ' each of the values is enclosed with double quotes
parser.TrimWhiteSpace = True
parser.ReadLine()
Do Until parser.EndOfData = True
consolDump1.Rows.Add(parser.ReadFields())
Loop
Dim strSql As String = "INSERT INTO consolDump(PO_Number,Consol_ID,Status,Contractor,UTAS_Owner,Description,Start_Date,End_Date,Total_Spend,Job_Title,Location,Type) VALUES (#PO_Number,#Consol_ID,#Status,#Contractor,#UTAS_Owner,#Description,#Start_Date,#End_Date,#Total_Spend,#Job_Title,#Location,#Type)"
Dim SqlconnectionString As String = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\consolData.mdf;Integrated Security=True;Connect Timeout=30"
Using connection As New SqlClient.SqlConnection(SqlconnectionString)
Dim cmd As New SqlClient.SqlCommand(Sql, connection)
' create command objects and add parameters
With cmd.Parameters
.Add("#PO_Number", SqlDbType.VarChar, 15, "PO_Number")
.Add("#Consol_ID", SqlDbType.BigInt, "Consol_ID")
.Add("#Status", SqlDbType.Text, "Status")
.Add("#Contractor", SqlDbType.Text, "Contractor")
.Add("#UTAS_Owner", SqlDbType.Text, "UTAS_Owner")
.Add("#Description", SqlDbType.Text, "Description")
.Add("#Start_Date", SqlDbType.Date, "Start_Date")
.Add("#End_Date", SqlDbType.Date, "End_Date")
.Add("#Total_Spend", SqlDbType.Money, "Total_Spend")
.Add("#Job_Title", SqlDbType.Text, "Job_Title")
.Add("#Location", SqlDbType.Text, "Location")
.Add("#Type", SqlDbType.Text, "Type")
End With
Dim adapter As New SqlClient.SqlDataAdapter()
adapter.InsertCommand = cmd
'--Update the original SQL table from the datatable
Dim iRowsInserted As Int32 = adapter.Update(consolDump1)
End Using
End Sub
There is an extra comma at the end of the column list in your sql query:
End_Date, Total_Spend, )
You need this:
End_Date, Total_Spend )
Also, the column list has 9 items, but your values list has 12. Are you maybe missing a few columns?
Finally for this section, it doesn't matter much with code for personal use, but what you're doing with string concatenation to put the excel data into your query is considered bad practice. If you do that in product code, you're creating a huge security hole. Instead, learn about parameterized queries.
In the later sample, you define your sql string this way:
Dim strSql As String
But try to include in your command this way:
Dim cmd As New SqlClient.SqlCommand(Sql, ...
You should do this:
Dim cmd As New SqlClient.SqlCommand(strSql, ...
Also, based on the other code, if this is an access database, you should still be using the OleDbCommand and OleDbConnection objects, in the System.Data.OleDb namespace.
What I would do is somewhere in between your first sample and your second:
Imports System.Data.SqlClient
Private Sub buttonConsolImport_Click(sender As Object, e As EventArgs) Handles buttonConsolImport.Click
Dim fBrowse As New OpenFileDialog
With fBrowse
.Filter = "Excel files(*.xls)|*.xls|All files (*.*)|*.*"
.FilterIndex = 1
.Title = "Import data from Excel file"
End With
If fBrowse.ShowDialog() <> Windows.Forms.DialogResult.OK Then Exit Sub
Dim fname As String = fBrowse.FileName
Dim sql As String = "INSERT INTO consolDump(PO_Number,Consol_ID,[Status],Contractor,UTAS_Owner,Description,Start_Date,End_Date,Total_Spend,Job_Title,Location,Type) VALUES (#PO_Number,#Consol_ID,#Status,#Contractor,#UTAS_Owner,#Description,#Start_Date,#End_Date,#Total_Spend,#Job_Title,#Location,#Type)"
Try
Dim parser As New FileIO.TextFieldParser(fname)
parser.Delimiters = New String() {","} ' fields are separated by comma
parser.HasFieldsEnclosedInQuotes = True ' each of the values is enclosed with double quotes
parser.TrimWhiteSpace = True
parser.ReadLine() 'skip column headers
Using cn As New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\consolData.mdf;Integrated Security=True"),
cmd As New SqlCommand(sql, cn)
With cmd.Parameters
.Add("#PO_Number", SqlDbType.VarChar, 15)
.Add("#Consol_ID", SqlDbType.BigInt)
.Add("#Status", SqlDbType.Text) 'I doubt that "Text" is the right type for all of these
.Add("#Contractor", SqlDbType.Text) 'If it is, you may want to examine your table schema
.Add("#UTAS_Owner", SqlDbType.Text)
.Add("#Description", SqlDbType.Text)
.Add("#Start_Date", SqlDbType.Date)
.Add("#End_Date", SqlDbType.Date)
.Add("#Total_Spend", SqlDbType.Money)
.Add("#Job_Title", SqlDbType.Text)
.Add("#Location", SqlDbType.Text)
.Add("#Type", SqlDbType.Text)
End With
cn.Open()
Do Until parser.EndOfData = True
Dim fields() As String = parser.ReadFields()
For i As Integer = 0 To 11
cmd.Parameters(i).Value = fields(i)
Next
cmd.ExecuteNonQuery()
Loop
End Using
MsgBox("Success")
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
I want to connect data from any folder in my computer.After user click browse button it appear any location for access database folder.After that user click connect button and but i have facing connection problem.
Under Browser Button
Using ofd As New OpenFileDialog
ofd.Filter = "mdb files |*.mdb"
ofd.Title = "Select File"
ofd.ShowDialog()
TextBox1.Text = ofd.FileName
If ofd.ShowDialog() = Windows.Forms.DialogResult.OK Then
MessageBox.Show("Hang amik " & TextBox1.Text)
End If
End Using
Under connect button
Dim connetionString As String
Dim cnn As OleDbConnection
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= & TextBox1.Text "
cnn = New OleDbConnection(connetionString)
Try
cnn.Open()
MsgBox("Connection Open ! ")
cnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
My main problem what code must inserted for connecting to database?
Data Source= & TextBox1.Text
My code not work.
Using Visual Studio 2010.vb.net.Thank You Very Much.
Fix:
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & TextBox1.Text
Use String.Format to best improve usability in build string with variables.