source name not found and no default driver specified 111 - vb.net

Hi Im trying to access MS ACCESS DB via VB and I get this error
ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
I have done:
Change IIS manager -application pool App32 bits to true
Downloaded DB drivers for Access
Install Access Client
Nothings working at the moment, I've tried from 2 diffrent computers
This is my code
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim vConnectionStringX As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\1767631\db_Assign_2.accdb;Persist Security Info=False;"
Dim rtfConn As New Data.Odbc.OdbcConnection(vConnectionStringX)
rtfConn.Open()
Dim cusFName As String = TextBox1.Text
Dim cusLName As String = TextBox2.Text
Dim cusTP As String = TextBox3.Text
Dim cusEmail As String = TextBox4.Text
Dim vSQL As String = "Insert into Customer(FirstName, LastName, Telephone, Email) Values (" & cusFName & "," & cusLName & "," & cusTP & "," & "cusEmail"")"
Try
Dim rtfSQLCMD As New Data.Odbc.OdbcCommand
rtfSQLCMD.Connection = rtfConn
rtfSQLCMD.CommandText = vSQL
Dim vResult As Integer = rtfSQLCMD.ExecuteNonQuery
MessageBox.Show("Customer registered! " & vResult)
Catch ex As Data.Odbc.OdbcException
Dim vErMsg As String = "*** Error occured while registering the customer ***" & ControlChars.NewLine
End Try
rtfConn.Close()
End Sub
Plese help me!

Your connection string is for OleDb connections and it is not valid for Odbc. you must use something like this for OdbcConnection:
Dim vConnectionStringX As String = "Driver={Microsoft Access Driver (*.mdb)};DBQ=c:\db1.mdb"
you also need to save your access database as '.mdb' file (eg Ms Access 2000 - 2003 format)
Note: There is also another option: if you don't have a reason to use Odbc, why you don't use OleDb which is usually used for microsoft access database? if you want to use OleDb you should use your original(current) connection string but use OleDbConnection for your connection variable and OleDbCommand for your command variable and so on.

Also, make sure you have updated VB6 for service pack SP6. It's required to handle MS Access 2000 and later.

Related

System.InvalidOperationException: ExecuteReader requires an open and available connection. The connection's current state is closed

I am having a problem with a customer service module which is in a different solution. the problem I think is in my method of calling or getting a connection
here is my class called DBConnForAccess
Imports System.Data.OleDb
Imports System.Data.Odbc
Public Class DBConnForAccess
Dim Conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim Trans As OleDbTransaction
Public Function DBConnect(ByVal filePath As String, pass As String)
Try
' open Database
'Conn = New SqlConnection("Data Source=" + ServerName + "\" + DBName + ";User ID=" + DBUsername + ";Password=" + DBPassword + ";Initial Catalog= '" + TB + "'")
Conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Jet OLEDB:Database Password=" + pass + ";")
' "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;Jet OLEDB:Database Password=MyDbPassword;"
If Conn.State = ConnectionState.Closed Then
Conn.Open()
End If
' create transaction
Trans = Conn.BeginTransaction
Return "Ok"
Catch ex As Exception
Return ex.Message
End Try
End Function
Public Sub ExecuteSQL(ByVal sql As String, ByVal ParamArray Obj() As Object)
' command Object
Dim CMD As New OleDbCommand(sql, Me.Conn, Me.Trans)
'add the parameters to the sql command
Dim I As Integer
For I = 0 To Obj.Length - 1
CMD.Parameters.AddWithValue("#" & I, Obj(I))
Next
'execute the sql
CMD.ExecuteNonQuery()
End Sub
Public Sub commit()
Me.Trans.Commit()
Me.Trans = Me.Conn.BeginTransaction
End Sub
Public Sub rollback()
Me.Trans.Rollback()
Me.Trans = Me.Conn.BeginTransaction
End Sub
Public Sub CloseDB()
Me.Conn.Close()
Me.Conn.Dispose()
Me.Trans.Dispose()
End Sub
Public Function ReadData(ByVal sql As String, ByVal ParamArray Obj() As Object)
' command Object
Dim CMD As New OleDbCommand(sql, Me.Conn, Me.Trans)
'add the parameters to the sql command
Dim I As Integer
For I = 0 To Obj.Length - 1
CMD.Parameters.AddWithValue("#" & I, Obj(I))
Next
Dim R = CMD.ExecuteReader()
'Do While R.Read
'Loop
Return R
End Function
End Class
Here is the Sub I use to fetch Data:
Dim connection As String = txt_util.readFromTextFile("ConnStr_2.txt", 0) + "Billing.mdb"
'connection string is in a text file with text at line 0 as "C:\BILLSERV\"
Private Sub searchAccnt(ByVal SIN As String)
'clear other fields
Clear("Acct")
Try
AccntDetail.DBConnect("ConcessionairesAccnt")
'Dim RS = AccntDetail.ReadData("Select * From AllAccounts Where SIN=#0", txtSIN.Text.Trim)
Dim RS = AccntDetail.ReadData("Select * From viewCSFAccnt Where SIN=#0", SIN)
RS.Read()
If RS.Hasrows = 0 Then
MsgBox("Accounts not found. Check the SIN you Enter.", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Records not found.")
'txtAppNo.Focus()
Exit Sub
Else
'MsgBox("Accounts correct.", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Records found.")
txtZoneNo.Text = RS.Item("Zone").ToString
txtSeq.Text = RS.Item("SeqNo").ToString
txtAccntName.Text = RS.Item("AccountName").ToString
txtAccntAddress.Text = RS.Item("HouseNo").ToString + " " + RS.Item("BLDGName").ToString + " " + RS.Item("Street").ToString + _
" " + RS.Item("BRGY").ToString
txtMeterNo.Text = RS.Item("MeterNo").ToString
txtAccntStatus.Text = varA.AccntStatus(RS.Item("Status").ToString)
'Dim con = AccessAccnt.DBConnect(connection, "")
'If con <> "Ok" Then
' MsgBox("Cannot establish a Connection to the server.", MsgBoxStyle.Critical, "Connection Lost...")
'End If
Dim ZoneNo = "Z" + GetChar(txtZoneNo.Text, 1) + GetChar(txtZoneNo.Text, 2) + "B" + GetChar(txtZoneNo.Text, 3) + GetChar(txtZoneNo.Text, 4)
AccessAccnt.DBConnect(connection, "")
Dim Acc = AccessAccnt.ReadData("SELECT * FROM " & ZoneNo & " WHERE AcctNo3=#1", txtSeq.Text)
Acc.Read()
txtLastReading.Text = Acc.Item("LastReading").ToString
Acc.close()
AccessAccnt.CloseDB()
End If
RS.Dispose()
AccntDetail.CloseDB()
dbCounter.DBConnect("ConcessionairesAccnt")
Dim result = dbCounter.ReadData("Select Top 1 CSFNo From CSFMaster WHERE (CSFNo LIKE '%" & ctrDate() & "%') order by CSFNo Desc")
result.read()
If result.hasrows = 0 Then
txtTrackingNo.Text = ctrDate() & "-" & "000001"
Else
txtTrackingNo.Text = counter.CtrLastItemWithChar("ConcessionairesAccnt", "CSFNo", "CSFMaster", "WHERE (CSFNo LIKE '%" & ctrDate() & "%') ORDER BY CSFNo DESC", 5)
End If
dbCounter.CloseDB()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
The Error is thrown here:
Dim Acc = AccessAccnt.ReadData("SELECT * FROM " & ZoneNo & " WHERE AcctNo3=#1", txtSeq.Text)
It Says:
System.InvalidOperationException: ExecuteReader requires an open and available connection. The connection's current state is closed.
The Other Parts of the Sub Works fine, The part where I fetch Data on my MSSQL Server database. The Problem lies in the Access data-Fetching Code.
I tried Using the code on another project (just the code where i fetch access data) I worked on other solutions. But I copy and paste my code on any form in this solution I keeps giving the Error.
I thought Maybe I closed the connection somewhere but this is the only instance I used this code in this entire project. (Just to get the last reading record.)
The Database is in the correct place (C:\BILLSERV)
I've Tried searching it here on SE but all I can see where suggestions about maybe forgetting to open the connection. I used this code before and this code works on my other solutions. I just cant seem to have it work here on this particular project. I wonder Why..
I tried running another project using this code and it works fine.
Is there a bug about Access connection on VB.net 2012, I have been using this code (DBConnForAccess Class) for about a year now and this is the first time I have encountered this error. btw I use Access 2003 because this database used to be for an old system created in VB6.
Lastly could this be because the solution came from another computer using a VB.Net Program same as mine. Because We work as a team here. Hope someone with a better knowledge on these systems could help. Thanks in advance.
EDIT
If a connection has been made, there should be a .ldb file in access which should appear. (I tested this on another project and an ldb file appear once a connection has been made, as we all know ldb file contains the data of the user using the db file.) I tried to re-run the system and while I'm using the system no ldb file was created.
Also,I thought Maybe I closed the connection somewhere but this is the only instance I opened a connection in access and which I used the code in this entire project. (Just to get the last reading record.)
So this is NOT a duplicate of “There is already an open DataReader…” Reuse or Dispose DB Connections? Just for clarifications
After a week of debugging and reading articles in the web.
We have found the culprit of the Error.
Seems that the Target CPU Option in Advance compiler Settings was change to AnuCPU.
We noticed this after we checked the other application projects we used.
Changing it Back to x86 solves the connection problem.
I wonder why this affected the connection to the access.
All is working fine now. thank you Plutonix and Steve for all your suggestions we'll be having a change in our codes.

i am trying to use an input from the user as part of a connection string to a SQL database

my connection string is saved in a string variable names str
what i am trying to do is use an input from the user as part of the string
the parts i want to take from the user are the ID and PASS
i am simply trying to check the connection statues with the ID and the PASS as inputs from the user.
Dim str As String = "Data Source=DESKTOP;uid=ID;pwd=PASS;database=DB"
Dim conn As New SqlConnection(str)
Private Sub btnconnect_Click(sender As Object, e As EventArgs) Handles btnconnect.Click
PW = txtadminpass.Text
Try
conn.Open()
conn.Close()
MsgBox("GOOD")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
i haven't had much like while using the + and & for the strings.
any help would be appreciated.
The SqlConnectionStringBuilder is an appropriate class to use in this case. You can add parts of the connection string to it via properties, so there is no chance of making mistakes:
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim csb As New SqlConnectionStringBuilder
csb.DataSource = "DESKTOP"
csb.InitialCatalog = "DB"
csb.UserID = "z"
csb.Password = "x"
' output "Data Source=DESKTOP;Initial Catalog=DB;User ID=z;Password=x" '
Console.WriteLine(csb.ToString())
Console.ReadLine()
End Sub
End Module
So, you need to check if the user is allowed to log into the database or not. The way you have followed looks good, you define the connection string based on the given ID and password, and you try to establish a connection, if it fails, the user can't log in, else he can do that.
However, the way you defined the string is wrong, you must use concatenation to preserve the ID and password values, try this,
Dim str As String = "Data Source=DESKTOP; uid=" & ID & "; pwd=" & PASS & ";database=DB"
Another way, which makes it easy to read:
Const CONN_STRING As String = "Data Source=DESKTOP;uid={0};pwd={1};database=DB"
Dim connString As String = String.Format(CONN_STRING, txtUserID.Text.Trim, txtPassword.Text)

Possible to query As400 DB2 via VB.Net without a PRG?

After spending a few days researching and trying to figure this out solo, I could really use some help.
I'm trying to query the As400's database directly from .Net without the use of a As400 program file. I have very little support other than "go ahead and try" from the As400 administrators (I'm being told what I'm attempting hasn't been done here before).
I'd really like to use CWBX. The code below successfully connects, but I could really use a pointer in the right direction on how to build a query:
Dim As400 As New AS400System
Dim AsProgram As New cwbx.Program
Dim AsCommand As New cwbx.Command
Dim strQuery As String
As400.Define("AS400")
As400.UserID = ""
As400.Password = ""
As400.IPAddress = ""
As400.Connect(cwbcoServiceEnum.cwbcoServiceRemoteCmd)
If As400.IsConnected(cwbcoServiceEnum.cwbcoServiceRemoteCmd) = 1 Then
MsgBox("Valid Connection")
Else
MsgBox("Invalid Connection")
Exit Sub
End If
'-----------------------------------------------------------------------------------------
'Trying to figure out first if this syntax is correct, and if so... where/how to call it??
'-----------------------------------------------------------------------------------------
strQuery = "SELECT * FROM Library.File WHERE FILEFIELD='Criteria'"
' ---
AsProgram.LibraryName = ""
AsProgram.ProgramName = "" '?
AsProgram.system = As400
'Assuming this will end up being a program call?
'AsProgram.Call()
As400.Disconnect(cwbcoServiceEnum.cwbcoServiceRemoteCmd)
I'm very open to any other methods/suggestions. I've looked for guides from IBM's site as well as MSDN and neither actually do direct querying without the use of an As400 program file. Is this even possible?
Here is a simple console app that will retrieve all the records from one table and display the row count.
Imports System.Data.OleDb
Module Module1
Sub Main()
Dim cmd As New OleDbCommand
Dim table As String = "YOUR TABLE"
cmd.CommandText = "SELECT * FROM " & table
Dim ip As String = "YOUR AS/400 IP GOES HERE"
Dim user As String = "YOUR USER ID"
Dim pass As String = "YOUR PASSWORD"
Dim defaultLib As String = "YOUR LIBRARY"
Dim connstring As String = "Provider=IBMDA400;" & _
"Data Source=" & ip & ";" & _
"Force Translate=0;" & _
"Default Collection=" & defaultLib & ";" & _
"User ID=" & user & ";" & _
"Password=" & pass
cmd.Connection = New OleDbConnection(connstring)
cmd.Connection.Open()
Dim dr As OleDbDataReader = cmd.ExecuteReader
Dim dt As New DataTable
dt.Load(dr)
Console.WriteLine(dt.Rows.Count)
Console.WriteLine("Press ENTER to close...")
Console.ReadLine()
End Sub
End Module
The remotecmd service is basically a Rexcd daemon. Not sure why you're messing with that when you want to simple query a DB table. The integrated DB in IBM i is accessible via ODBC, OLEDB, JBDC and most importantly for you a ADO.NET provider.
http://www-03.ibm.com/systems/power/software/i/access/windows/dotnet.html
All of the above mentioned drivers are available in the IBM i Access software. Note that while some of the IBM i Access features are chargeable, ex 5250 emulation, and you must have bought a license; the data access providers are not.
Included in the IBM i Access package is a collection of documentation known as the "Programmers Toolkit"
An example using the .NET data provider from that toolkit:
Public Sub Example()
Dim cn As iDB2Connection = New iDB2Connection("DataSource=mySystemi;")
Dim da As New iDB2DataAdapter("select * from mylib.mytable", cn)
End Sub
Lastly note that the (free) .NET provider doesn't support Microsoft's Entity Framework (EF). If you need EF support, you'll have to pay for DB2 Connect
http://www-03.ibm.com/software/products/en/db2-connect-family

How to load data from oracle database using .dsn? (VB.NET)

I'm trying to test if the connection from my utility to oracle DB is working by using .dsn . I've searched from many forums but to no avail . Here is my code:
Dim filedsn As String = "C:\my_dsn.dsn"
Dim uid As String = "id123"
Dim pwd As String = "1234"
Dim cn As OdbcConnection
cn = New OdbcConnection("Driver=Oracle in OraClient11g_home2;Provider=msdaora;dsn=" & filedsn & ";uid=" & uid & ";pwd=" & pwd & ";")
Dim mystring As String = "Select * from DD_CADS1.PDTABLE_12_1001"
Dim cmd As OdbcCommand = New OdbcCommand(mystring)
cn.Open()
MsgBox("Connected")
cn.Close()
But these error appears..
ERROR [HY000] [Oracle][ODBC][Ora]ORA-12560: TNS:protocol adapter error
ERROR [IM006] [Microsoft][ODBC Driver Manager] Driver's SQLSetConnectAttr failed
ERROR [HY000] [Oracle][ODBC][Ora]ORA-12560: TNS:protocol adapter error
Can you tell me what's the problem with my codes? Is there any other way to connect to oracle database through .dsn using VB.net? I'm currently using ** Oracle 11g**.
The biggest problem in your code is that you use ODBC to connect to Oracle. You should use ODP.NET, which is even recommended by Microsoft. What you doing is there [most likely] for backwards compatibility and not to write the new stuff.
Here your problem is in connection string, which should look like this
"DSN=oracledsn;UID=myUID;PWD=myPWD;Integrated Security=no;"
And you don't need command just to test connection
using cn= New OdbcConnection(".....")
cn.Open()
if cn.State = ConnState.Open Then MessageBox.Show(...)
end using
When you use using it will take care of closing and disposing of connection.

How to use 2 connection objects while importing data from one database to another in vb.net

I am using the following code to select from one database and need to insert into another database.. Please suggest me the code:
Code :
'Connection for Original database from where i have to import
Dim constrOrg As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strPath
Dim conn_OrgDB As New OleDb.OleDbConnection(constrOrg)
'Connection for my database to where i have to import
Dim App_Path = System.AppDomain.CurrentDomain.BaseDirectory()
Dim constr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + App_Path + "Mydb.accdb"
Dim cnnOLEDB As New OleDb.OleDbConnection(constr)
Dim strSelInv_one As String = ("SELECT * FROM INV_ONE where (DOCU_DT>=#stdt AND DOCU<=#enddt) ")
Dim comm_inv_one As OleDb.OleDbCommand = New OleDb.OleDbCommand(strSelInv_one, conn_OrgDB )
comm_inv_one.Parameters.AddWithValue("#stdt", StTime)
comm_inv_one.Parameters.AddWithValue("#enddt", Endtime)
dr = comm_inv_one.ExecuteReader
Do While dr.Read = True
Dim strInsInv1 As String = "INSERT INTO INVOICE_ONE(CODE_NO,LAY,..) SELECT CODE_NO,LAY,... FROM INV_ONE where (CODE_NO=#code)"
Dim comm_Insinv1 As OleDb.OleDbCommand = New OleDb.OleDbCommand(strInsInv1, cnnOLEDB)
comm_Insinv1.Parameters.AddWithValue("#code", Code_no)
comm_Insinv1.ExecuteNonQuery()
Loop
'Here INVOICE_ONE table belongs cnnOLEDB connection obj of one database and INV_ONE table belongs to conn_OrgDB connection object of another database..
' How to use the 2 connection object ? If i use only one connection object i.e. cnnOLEDB it gives the following Error:
" The Microsoft Office Access database engine cannot find the input table or query 'INV_ONE'. Make sure it exists and that its name is spelled correctly. "
Please suggest me the code..
Thank you
try this code, obviously don't make it as long as his ( basically wack out stuff you don't need and imput your code, now ....
in addition to :
Dim connectionStr = Constants.Input.MDB.CONNECTION_STRING & _
"Data Source=" & dbFullPath & ";"
Dim connection As New System.Data.OleDb.OleDbConnection(connectionStr)
in addition use
Dim connectionStr2 = "Other conection string"
Dim connection2 As New System.Data.OleDb.OleDbConnection(connectionStr)
and import it into his code.
link:
Selecting data in MS Access with vb.net is very slow. Am I doing it right?
I am sorry if this won't help, since i don't have an access db i cannot further test this.
Reguards.
My suggestion would be use to Access to create Linked Tables in the target database that point to the corresponding tables in the source (production) database. Then you can at least manipulate both sets of tables using the same connection, thereby giving you the option of doing
INSERT INTO INVOICE_1 (codeno, lchlndt, ...)
SELECT codeno, lchlndt, ... FROM INV_ONE ...