VB.NET connection to MS Access - vb.net

I get an error when I am trying to connect to a Microsoft Access DB using VB.NET. I see examples all over the web. My code looks like those examples, however I am getting a build error message stating:
Type 'System.Data.OleDb.OleDbConnection' is not defined.
I have tried adding some kind of import statement for the system.data.oledb... but that does not seem to work. My code is below. It is a basic connection so I am thinking that I am missing some kind of add in, library, or setting. Any and all help would be greatly appreciated.
Public Function TestMain(ByVal args() As Object) As Object
' Connection String to MS Access DB
Dim connectStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Users\DMalerman\keyword.accdb;" & _
"Persist Security Info=False;"
MsgBox(connectStr)
' Create connection to the db
Using connection As New System.Data.OleDb.OleDbConnection(connectStr)
' Create the SQL Query
Dim readQuery As String = "Select KeywordDriver.ScriptName from KeywordDriver " & _
"where KeywordDriver.Keyword = test"
Dim queryCommand As New System.Data.OleDb.OleDbCommand(readQuery, connection)
'Open the Connection
connection.Open()
' Query the Database
Dim dbReader As System.Data.OleDb.OleDbDataReader = queryCommand.ExecuteReader()
' Loop until there is nothing left to read
While dbReader.Read()
Dim sKeyword As String = ""
sKeyword = dbReader.GetString(0)
MsgBox(sKeyword)
End While
' Close the Reader
dbReader.Close()
End Using
Return Nothing
End Function

did you try
imports System.Data.OleDb
?
if so, did it give you an error?

Please try to modify this line:
Dim queryCommand As New System.Data.OleDb.OleDbCommand(readQuery, connection)
by putting these only:
Dim queryCommand As New System.Data.OleDb.OleDbCommand(readQuery)
queryCommand.Connection = connection

Imports System.Data
Imports System.Data.OleDb
Module Module1
Public str As String
Public con As OleDbConnection
Public cmd As OleDbCommand
Public dtreader As OleDbDataReader
Public dtadapter As OleDbDataAdapter
Public Sub openconn()
str = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Database2.mdb"
con = New OleDbConnection(str)
Try
con.Open()
Catch ex As Exception
MessageBox.Show("gagal koneksi")
End Try
End Sub
End Module

Related

Connect to a database with visual basic

I am trying to connect an database, but it crash and it say that there are a
Connection problem, i have tryed this code in other pc, but now does not work
the error is:
There was a network or instance-specific error while trying to establish a connection to SQL Server. The server was not found or is not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
the code is this:
Module Module1
'FUNZIONE PER LA CONNESSIONE AL DATABASE
Public Function Connetti(ByVal sql As String, ByVal namedset As String, ByRef dataSet As DataSet)
Dim myConnString As String = "Persist Security Info=False;database=test;server=95.134.229.235;user id=web;pwd=fiautoppzione" 'server=Server206 'user id=utente_std;pwd=145111
Dim myConnection As New SqlConnection(myConnString)
Dim myInsertQuery As String = sql
Dim myCommand As New SqlCommand(myInsertQuery)
Dim myada As New SqlDataAdapter
Dim mydset As New DataSet(namedset)
Dim mydbs As New BindingSource
'IO.File.AppendAllText("C:\aggiorna.txt", sql & vbCrLf)
myCommand.Connection = myConnection
myada.SelectCommand = myCommand
myada.MissingSchemaAction = MissingSchemaAction.AddWithKey
mydset.EnforceConstraints = False
mydset.Clear()
myada.Fill(mydset, namedset)
mydbs.DataSource = mydset.Tables(namedset)
If Mid(sql, 1, 6) = "update" Then
mydset.Clear()
myada.Fill(mydset, namedset)
mydbs.DataSource = mydset.Tables(namedset)
End If
myConnection.Open()
dataSet = mydset
myCommand.Connection.Close()
Return mydbs
End Function
and the first part of the code:
Option Explicit On
Imports System.Data
Imports System.Data.Odbc
Imports System.Xml.Xsl
Imports System.ComponentModel
Imports System.Threading
Imports System.IO.Ports
Imports FIAppStabilimento.MySql.Data
Imports System.Data.SqlClient
Namespace MySql.Data.MySqlClient
End Namespace
For mySQL connection, you must not use the sqldataconnection.
First download MySql Connector/Net
Then add the following reference:
MySQL.Data
Sometimes MySql for somehow is not listed under .NET tab. Go to Browse tab, and navigate to the following path:
C:\Program Files (x86)\MySQL\MySQL Connector Net 6.6.4\Assemblies\v2.0
or C:\Program Files (x86)\MySQL\MySQL Connector Net 6.6.4\Assemblies\v4.0
and add MySql.Data.dll
Add the following code before Public Class Form1
MYSQL.dll Reference Image
Imports MySql.Data.MySqlClient
Then add the following declaration below Public Class Form1
Dim conn As New MySqlConnection
Public Sub connect()
Dim DatabaseName As String = "test"
Dim server As String = "95.134.229.235"
Dim userName As String = "web"
Dim password As String = "fiautoppzione"
If Not conn Is Nothing Then conn.Close()
conn.ConnectionString = String.Format("server={0}; user id={1}; password={2}; database={3}; pooling=false", server, userName, password, DatabaseName)
Try
conn.Open()
MsgBox("Connected")
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close()
End Sub

InvalidCastExeption when trying to dim a string

Im having a problem when trying to run my code. Im new to stackoverflow but will try to explain my problem.
Well, i get a "InvalidCastExeption" with the explanation
"Converson from string "Filename" to type "Integer" is not valid.
The confusing part is that FileName is a nvarchar(30) in my SQL database, and sName a string.
Look at the code, it failes at the dim sName = ...
Ps - I have tried to convert.toint / Cint, but it doesnt help. AND i want it as a string, not a integer!
Imports System
Imports System.Data
Imports System.Data.SqlClient
Public Class SelectrecipieDatabaseManager
Private Const CONNECTION_STRING As String = "Data Source=RYOW701;Initial Catalog=RyReci;Integrated Security=True"
Private connection As SqlConnection = Nothing
Private command As SqlCommand = Nothing
Public Sub RecipieHandler(ByVal Choice As String)
Dim reader As SqlDataReader
connection = New SqlConnection(CONNECTION_STRING)
Try
connection.Open()
Dim Query As String
Query = "select * from TbNew"
command = New SqlCommand(Query, connection)
reader = command.ExecuteReader
While reader.Read
Dim sName = reader.GetString("FileName")
RecipieForm.ComboBoxRec.Items.Add(sName)
End While
Catch ex As SqlException
MessageBox.Show(ex.Message)
Finally
connection.Close()
connection.Dispose()
End Try
End Sub
End Class
The getString method expects an ordinal number as it's parameter, not a string. Do this instead:
reader = command.ExecuteReader
Dim columnID As Integer = reader.GetOrdinal("FileName")
While reader.Read
Dim sName = reader.GetString(columnID)
RecipieForm.ComboBoxRec.Items.Add(sName)
End While

Query SQL Database and Store Results in a Variable VB.Net

I am trying to query a SQL DB using a textbox field and retreive a column from the DB and store it in a variable so I can use it in other places within my site. My web form requires the user to enter a few items such as name and zip code.
My database has 3 columns; email address, zip code, and id. I need the input form to query the database and return the "email address" that matches the user's inputted "zip code"
I understand the SQL SELECT statement and the connection string is correct. My queries are working, I just can't seem to figure out how to get the returned "email address" to store in a variable. Any help would be appreciated.
Dim strconnection As String, strSQL As String, strZipCheck As String
Dim objconnection As OleDbConnection = Nothing
Dim objcmd As OleDbCommand = Nothing
Dim RREmail As String = Nothing
Dim zipQuery As String = zipCodeBox.Text
'connection string
strconnection = "provider=SQLOLEDB;Data Source=XXX.XXX.XXX.XXX;Initial Catalog=XXXXXXX;User ID=XXXX;Password=XXXXXXXX;"
objconnection = New OleDbConnection(strconnection)
objconnection.ConnectionString = strconnection
'opens connection to database
objconnection.Open()
strSQL = "SELECT [EMAIL ADDRESS] FROM ZIPCODEDATA WHERE [ZIP CODE] = #ZIP CODE "
objcmd = New OleDbCommand(strSQL, objconnection)
RREmail = CType(objcmd.ExecuteScalar(), String)
lblRREmail.Text = RREmail
objconnection.Close()
While the other comments do point out particular deficiencies with your syntax, I would like to address the question of storing a variable and take it a bit further. I generally do not use parameterized connections unless I am calling stored procedures and need an output parameter. Instead, here is what I often do to create a database connection and get my results.
First I create a public class called dbConn so I dont have to write it out a million times.
Imports System.Data.SqlClient
Public Class dbConn
Public Property strSQL As String
Private objConn As SqlClient.SqlConnection = _
New SqlClient.SqlConnection("Data Source=(local)\dev;Initial Catalog=testDataBase;Persist Security Info=False;Integrated Security = true;")
Public Function getDt() As DataTable
Dim Conn As New SqlClient.SqlConnection
Dim da As SqlClient.SqlDataAdapter
Dim dt As New DataTable
Try
objConn.Open()
da = New SqlClient.SqlDataAdapter(strSQL, objConn)
da.Fill(dt)
da = Nothing
objConn.Close()
objConn = Nothing
Catch ex As Exception
objConn.Close()
objConn = Nothing
End Try
Return dt
End Function
End Class
Then from another class (lets assume its form1) I call up that function to get a datatable returned to me. In this case I select TOP 1 to save your sanity in case by chance there is more than one email address per zip code.
Public sub getdata()
Dim strEmailAddress As String = Nothing
Dim dt As New DataTable
Dim da As New dbConn
da.strSQL = " select top 1 [email address] from [zipcode] " _
& " where [zip code] = '" & strZipCode & "'" _
& " order by [email address] asc"
dt = da.getDt
If dt.Rows.Count > 0 Then
If Not IsDBNull(dt.Rows(0)(0).ToString) Then
strEmailAddress = dt.Rows(0)(0).ToString
End If
End If
End Sub
From there you can use strEmailAddress within the sub after it is set, or you can move the string declaration outside of the sub as a public string declaration to use it elsewhere, or you can create other classes like an email class with a public property for strEmailAddress to pass it off to, etc.
I hope something in there helps you understand how to deal with your problem.

Declaration Expected

Good day all. Please advise me
Why I got an error message "Declaration Expected" when put the cursor on cmd variable. What Should I do?! .. the code appears below:
Imports System.Data.Sqlclient
Imports System.Configuration
Partial Class _Default
Inherits Page
Private Shared Connectionstr As String ="DataSource=localhost;initialCatalog=Orders;Integrated Security=true"
Dim conn As SqlConnection = New SqlConnection(Connectionstr)
Dim cmd As SqlCommand = conn.CreateCommand()
cmd.CommandText="SELECT * FROM dbo.Customers"
End Class
You are attempting to use the variable command outside a Property, Function, or Method. At the very least, try wrapping your command in a method (Sub) which performs the desired action with the data:
Partial Class _Default
Inherits Page
Private Sub DoSomethingWithCustomers()
Dim conn As SqlConnection = New SqlConnection(Connectionstr)
Dim cmd As SqlCommand = conn.CreateCommand()
cmd.CommandText = "SELECT * FROM dbo.Customers"
conn.Open()
Dim dr = cmd.ExecuteReader()
' Do something with the data returned . . .
' ...
' Now Cleanup:
conn.Close()
cmd.Dispose()
conn.Dispose()
End Sub
The above can be improved by wrapping your data access objects in Using blocks, which handle proper disposal of unmanaged resources for you:
Private Sub DoSomethingBetterWithCustomers()
Dim SQL As String = "SELECT * FROM dbo.Customers"
Using conn As New SqlConnection(Connectionstr)
Using cmd As New SqlCommand(SQL, conn)
conn.Open()
Dim dr = cmd.ExecuteReader()
' Do something with the data returned
' . . .
dr.Close()
End Using ' Using Block takes carre of Disposing SqlCommand
End Using ' Using Block takes care of Closing and Disposing Connection
End Sub
Beyond that, it is difficult to know what, precisely, you are trying to do with your code, so the two examples above are really, really basic and general.

vb.net generalized write of data to excel

I need to create an excel file from scratch in VB.NET given a DataTable from asp.net.
I can do this for a specific file, but I don't know how to do it for a general database.
That is, where I use the "CREATE TABLE ..." I don't know how to tell it what types to use for the data in the table.
The DataTable is derived from a FoxPro database. (I don't know if that matters.)
I invoke the table similar to as follows:
<%
return_value = make_excel( sql_table, excel_filename)
%>
make_excel is defined as
Option Explicit On
'Option Strict On
Imports System
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.Page
Imports System.IO
Imports Microsoft.VisualBasic
Imports System.Diagnostics
Imports System.Data
Imports System.Data.OleDb
Public Class clsCommon
Inherits Page
' buncha other stuff defined in here.
Public Shared Function make_excel(ByVal sqlTable As DataTable, ByVal xls_fn As String) As Boolean
Dim conn As System.Data.OleDb.OleDbConnection
Dim ds As System.Data.DataSet
Dim cmd As New System.Data.OleDb.OleDbCommand()
conn = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & xls_fn & "';Extended Properties=Excel 8.0;")
conn.Open()
cmd.Connection = conn
cmd.CommandText = "CREATE TABLE MyTable ( Admin char(20), first_name char(20));"
cmd.ExecuteNonQuery()
cmd.CommandText = "INSERT INTO MyTable ( Admin, first_name ) VALUES ('true', 'Bob')"
cmd.ExecuteNonQuery()
conn.Close()
Return True
End Function
End Class
What I need to be able to do is run through the values in sqlTable above, check their type and then build the sql to write them. Pointers?
Have you looked into the copyfromrecordset function? You'll need to do a bit of work and its a bit of a change of approach but it might be something you can look into. An MS article is available here (Sorry, the article is based around VBA, but it should help as a guide).
I have a solution to the problem. I'm not happy about it as a general solution, but it works well enough for the cases I'm currently dealing with.
In this solution, I create a template of the excel file that has the column headings I want to use. When I do the select in the forward code, I change the name of the fields as appropriate (or drop whatever fields I don't want).
Public Shared Function TestXL(ByVal resp As HttpResponse, ByVal sqlTable As DataTable, ByVal xls_template_fn As String, ByVal xls_fn As String) As Boolean
Dim conn As System.Data.OleDb.OleDbConnection
Dim ds As System.Data.DataSet
Dim cmd As New System.Data.OleDb.OleDbCommand()
Dim r As DataRow
Dim c As DataColumn
Dim i As Integer
Dim sql As String
dim str as string
If File.Exists(xls_template_fn) Then
try
If File.Exists(xls_fn) Then
File.Delete(xls_fn)
Else
File.Copy(xls_template_fn, xls_fn)
End If
catch ex1 as Exception
File.Copy(xls_template_fn, xls_fn)
End Try
Else
resp.Write("Unable to locate template file: " & xls_template_fn)
Return False
End If
conn = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & xls_fn & "';Extended Properties=Excel 8.0;")
conn.Open()
cmd.Connection = conn
cmd.CommandText = sql
For Each r In sqlTable.Rows
sql = "INSERT INTO MyTable ("
For i = 0 To sqlTable.Columns.Count - 1
sql = sql & " " & sqlTable.Columns(i).ColumnName & ","
Next
sql = Left(sql, sql.Length - 1) & " ) VALUES ( "
For i = 0 To sqlTable.Columns.Count - 1
str = r(i).toString()
dim str2 as string = str.replace("'", "''")
sql = sql & " '" & str2 & "',"
Next
sql = Left(sql, sql.Length - 1) & " );"
'resp.Write(sql & "<br/>")
cmd.CommandText = sql
cmd.ExecuteNonQuery()
Next
conn.Close()
Return True
End Function
Note the name of the the worksheet is the name of the table for the oledb call.
There's a link to other ways of doing this:
http://blogs.msdn.com/b/erikaehrli/archive/2009/01/30/how-to-export-data-to-excel-from-an-asp-net-application-avoid-the-file-format-differ-prompt.aspx
If I have to revisit this problem I'll probably start there.