select data from Dataset Vb.Net - vb.net

ok first ill explain what ive done.
First I imported an access db into my vb app it then named the dataset etc.
this is how my dataSet looks:
1 table
4 columns
so Far i have this:
Dim ds As ElementsDataSet
Dim dt As ElementsDataSet.ElementsDataTable
Dim conn As SqlConnection = New SqlConnection("Data Source=|DataDirectory|\Elements.accdb")
Dim selectString As String = "Select Atomic Mass FROM Elements WHERE No =" & mol
Dim cmd As New SqlCommand(selectString, conn)
If conn.State = ConnectionState.Closed Then conn.Open()
Dim datareader As SqlDataReader = cmd.ExecuteReader()
While datareader.Read = True
MessageBox.Show(datareader.Item("Atomic Mass"))
End While
datareader.Close()
and upon executing this I get this error:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

The problem is you are using a SQLConnection to open a Access database. This wont work.
You either need a SQLServer database or to use the OleDbConnection for a Access database.
Here is a Microsoft KB article to help you connect to the Access database:
How To Retrieve and Display Records from an Access Database by Using ASP.NET, ADO.NET, and Visual Basic .NET and this one over at CodeProject: http://www.codeproject.com/Articles/8477/Using-ADO-NET-for-beginners
Private Sub ReadRecords()
Dim conn As OleDbConnection = Nothing
Dim reader As OleDbDataReader = Nothing
Try
conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Temp\Elements.accdb"))
conn.Open()
Dim cmd As New OleDbCommand("Select Atomic Mass FROM Elements WHERE No =" & mol, conn)
reader = cmd.ExecuteReader()
While reader.Read = True
MessageBox.Show(reader.Item("Atomic Mass"))
End While
Finally
If reader <> Nothing Then
reader.Close()
End If
If conn <> Nothing Then
conn.Close()
End If
End Try
End Sub

Related

VB.NET - Key word is not supported: provider

When I try to connect to AcessDB, I get the error
"Keyword is not supported: provider".
When I try to change provider, I get another error. When I delete provider tag, I also get an error.
Dim Exists As Boolean = False
Dim ConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Name\Documents\Visual Studio 2010\Projects\datagrid\datagrid\pokus.accdb;Persist Security Info=False;"
Dim connection As New SqlConnection(ConnectionString)
Try
connection.Open()
Dim command As SqlCommand = connection.CreateCommand
command.CommandText = "SELECT * FROM studenti"
Dim reader As SqlDataReader = command.ExecuteReader
If reader.HasRows Then
Exists = True
Else
Exists = False
End If
reader.Close()
command.Dispose()
Catch ex As Exception
Console.Write(ex.Message)
Finally
connection.Close()
End Try
SqlConnection, SqlCommand, etc. are SQL Server-specific classes. You can't use them to connect to MS Access.
The documentation for SqlConnection makes this very clear:
Represents an open connection to a SQL Server database.
Consider using the OldDbConnection and related classes instead.
I always write wrapper classes for database connections, and I always recommend the same.
Dim sConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Name\Documents\Visual Studio 2010\Projects\datagrid\datagrid\pokus.accdb;Persist Security Info=False;"
Dim Conn As New OleDbConnection
Conn.ConnectionString = sConnectionString
Conn.Open()
Dim sQuery As String = "SELECT * FROM studenti"
Dim da As New OleDbDataAdapter(sQuery, Conn)
Dim dt As New DataTable
da.Fill(dt)
Conn.Close()

Executing an SQL query in an Access Database in VB.NET

I have already posted one question about this piece of code before lol. But now I am having a different problem and need help with it. Basically this is code for a search button on a Windows Form coded in VB.NET.
Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click
Dim cnnOLEDB As New OleDbConnection
Dim cmdOLEDB As New OleDbCommand
Dim strConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & System.Environment.CurrentDirectory & "\All Keyed Up, Lock & Safe, LLC.accdb"
cnnOLEDB.ConnectionString = strConnectionString
cnnOLEDB.Open()
Dim Connection As New SqlClient.SqlConnectionStringBuilder
Connection.DataSource = "file:///C:\Users\thelukester145\Documents\All%20Keyed%20Up\All%20Keyed%20Up,%20Lock%20&%20Safe,%20LLC.accdb"
Dim objSQLConnection = New SqlClient.SqlConnection(Connection.ConnectionString)
Dim cmd As New SqlCommand()
Dim myTable As New DataTable()
Dim SearchFor = SearchBox.Text
If AddressButton.Checked Then
cmd.Connection = objSQLConnection
cmd.CommandText = "SELECT * FROM [McDonald's-Corporate Stores] WHERE [Address] LIKE '%" & SearchFor & "%'"
Dim myAdapter As New SqlDataAdapter(cmd)
myAdapter.Fill(myTable)
DataGrid.DataGridView1.DataSource = myTable
ElseIf NumberButton.Checked Then
cmd.Connection = objSQLConnection
cmd.CommandText = "SELECT * FROM [McDonald's-Corporate Stores] WHERE [McOpCo#] LIKE '%" & SearchFor & "%'"
Dim myAdapter As New SqlDataAdapter(cmd)
myAdapter.Fill(myTable)
DataGrid.DataGridView1.DataSource = myTable
End If
DataGrid.Show()
cnnOLEDB.Close()
End Sub
The database that is attempting to be searched is a database of customers for our family buisness. I am trying to search by either the address or store number of our customer. I've worked through who knows how many fatal errors but the newest one has me sort of stumped. It is crashing on myAdapter.Fill(myTable). The error message it gives is this:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 25 - Connection string is not valid)
Any help would be much appreciated :)
Well, you are freely mixin OleDb classes with SqlClient classes. The two are for different database types. OleDb is needed for Access, SqlClient classes are used for Sql Server.
So you need to change all the classes SqlCommand, SqlCommandBuilder, SqlDataAdapter,SqlConnectionStringBuilder with the corresponding classes OleDbCommand, OleDbCommandBuilder, OleDbDataAdapter, OleDbConnectionStringBuilder
Infact, the error message is emitted by the SqlClient library that tries to use your connection string as it was a connectionstring for an SQL Server database and, of course, it fails to find it.
Also, I am not sure about that, but probably the DataSource property doesn't need the prefix file:/// and the Encoding of spaces with %20

Connecting to local sql server in vb.net - Error Connecting and difference between Local and Commercial?

I am a developer building websites in VB.Net using Visual Studio 2010. I am trying to populate some fields when a user visits a website based on their decisions on a previous screen.
My connection information is as follows:
Dim myDataReader As SqlDataReader
Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim strSQL As String
myConnection = New SqlConnection("Data Source=localhost\sqlexpress; Database=PREP; Integrated Security=SSPI;")
Try
myConnection.Open()
Catch ex As Exception
MsgBox(ex.Message)
End Try
strSQL = "SELECT * FROM Charts where ID=1"
myCommand = New SqlCommand(strSQL, myConnection)
myDataReader = myCommand.ExecuteReader()
If myDataReader.Read() Then
TextBox1.Text = myDataReader.Item("Priority1")
Else
MsgBox("Didn't work...")
End If
The error I continue to get is:
Cannot open database "PREP" by the login. The login failed. Login failed for user 'OR-AA-Me\Me'
I assumed that since it was a local database I would not need a username and password. Am I wrong?
Also, are there glaring practices in the above code that will be unwise when I transport this to a commercial environment?
Thanks!
Solved:
The connection string simply needed additional filepath information.
The successful connection information was:
myConnection = New SqlConnection("Data Source=.\SQLEXPRESS; AttachDbFilename=|DataDirectory|\PREP.mdf; Integrated Security=True; User Instance=True")
There was no need for a username as the Integrated Security set to True assumes that the computer will use the login information for the user on the actual computer he is using.

data source name not found

trouble connecting to postgresql database using odbc connector(x64) on vb.net console application(x64), the error,
http://www.sumarlidason.com/tmp/120312/odbc_capture1.png
Dim ConnectionString = "Driver={PostgreSQL UNICODE};Server=myPGSrv;Port=5432;Database=dbDefault;Uid=postgres;Pwd=pw;"
'Dim ConnectionString = "ODBC;dsn=PostgreSQL35W"
conn = New OdbcConnection(ConnectionString)
'Open connection to an instance of the PostgreSQL database.
Try
conn.Open()
Catch Ex As Exception
MsgBox(Ex.Message)
End Try
Dim commonOdbcCommand = New OdbcCommand
commonOdbcCommand.Connection = conn
conn.Close()
Also, I configured the database in the control panel, see here..
http://sumarlidason.com/tmp/120312/odbc_capture.png
correct connection string:
Dim conn As New OdbcConnection("DSN=PostgreSQL35W")

Search button error

I have a search button to search the database by a name entered in a text box, this is working fine within visual studio but when trying to use this in the hosted version i get the following message:
Server Error in '/' Application.
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
the code for this button is:
GridView2.Visible = True
lblEnterName.Text = ""
If txtLoanName.Text = "" Then
lblEnterName.Text = "Please enter a Bandie's Name"
Else
Dim conn As SqlConnection = Nothing
Try
Dim connString As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BandDatabase.mdf;Integrated Security=True;User Instance=True"
conn = New SqlConnection(connString)
Dim query As String = "SELECT [SongName], [PartLearnt], [Status] FROM [Learning] WHERE ([BandieName] LIKE '%' + #Name + '%') ORDER BY [SongName]"
Dim cmd As SqlCommand = New SqlCommand(query, conn)
cmd.Parameters.AddWithValue("#Name", txtLoanName.Text)
conn.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Dim dt As DataTable = New DataTable()
dt.Load(dr)
GridView2.DataSource = dt
GridView2.DataBind()
lblSearchBandieName.Text = "Progress for " + txtLoanName.Text
Finally
conn.Close()
End Try
End If
I am unsure why this is bringing the error as didnt before, all i have done is changed the page the button is on.
Thanks
did you check the information in the connection string? probably not an sqlexpres on the hosted solution. Also you may want to have the connection info in the web.config
Now as an answer....: -)