Access remote sql server using VB.NET - sql

I've found a few examples of using vb.net to access an sql database, so far none of them have worked . They all involve using DataReaders. Maybe its the fact that the sql db is not on the same machine as the application.
I was just wondering if anyone had a more comprehensive example of using VB.NET to access a remote sql server.
Thanks!
EDIT:
I've received a few helpful comments an replies already. So far my connection string looks like:
"server=sqlblah.myhost.com;uid=myuser;pwd=pass;database=testdb"
Probably also good to mention their is no editing of the tables a this point, just reading.

Check out the SQLClient class.
One convienent way to access a SQL database is to fill a DataSet object with query data with a DataAdapter object.
Dim sSQL As String = "SELECT * FROM ???"
Dim conn As New SqlClient.SqlConnection("connection string")
Dim da As New SqlClient.DataAdapter(sSQL, conn)
Dim ds As New DataSet
da.Fill(ds, "TABLE NAME")
You can then access the "TABLE NAME" table in the DataSet object.
The "connection string" is obviously your SQL connection string.
Use the sSQL string to query as necessary.

Quick side note - a helpful tool for creating connection strings:-
Open up a text document (notepad, wordpad etc) and save a blank document with the extension ".UDL".
This will give you a "Data link Properties" mini app.
Open up the app and change the provider in the "Provider" to whichever provider you need (in this case OLE DB Provider for SQL Server).
You then need to build up the connection in the connection tab.
Once you have chosen the criteria (ServerName (the drop down list will show you all visible Servers), Security permissions,Database (this drop down list will be populated based on the server chosen)) you can test your connection (to make sure you have permissions etc).
Click ok to close the App, rename the file to have a ".txt" extension and re-open in a text editor, hey presto, one built up connection string (as below).
Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=YOURDBNAME;Data Source=YOURSERVERNAME

Related

Accessing Oracle SQL Developer database from VBA

New to VBA and returning to SQL after 15 years. I'm am trying to use VBA to run SQL commands to download data into excel for further manipulation.
I have SQL Developer installed on my machine and I am able to access the database using the UI. I have figured out how to connect to the database and run a query within the SQL Developer interface, but honestly, I'm not an IT guy.
Any ideas how to do this? Even basic command line commands to connect to the database and run the query would be helpful.
I found this code on another site, but I'm having trouble getting my connection string to work. My macro errors out on the cnn.Open statement and says the Provider is not installed. I think it's because PROVIDER is set up for a different SQL Database type, but I can't seem to get the connection string to work.
I know my username and password, which I have successfully used to connect in the SQL Developer UI. I'm not sure what to put for remote IP address or database. Would that be the hostname and the SID in the connection properties dialog in SQL Developer? (The hostname looks more like a url without the http than an ip address. Not sure if hostname and ip address is an interchangeable term).
Sub Download_Reports()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String
'Setup the connection string for accessing MS SQL database
'Make sure to change:
'1: PASSWORD
'2: USERNAME
'3: REMOTE_IP_ADDRESS
'4: DATABASE
ConnectionString = "Provider=ORAOLEDB.ORACLE;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"
'Opens connection to the database
cnn.Open ConnectionString
'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
cnn.CommandTimeout = 900
'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
StrQuery = "SELECT TOP 10 * FROM tbl_table"
'Performs the actual query
rst.Open StrQuery, cnn
'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
Sheets(1).Range("A2").CopyFromRecordset rst
End Sub
I'm needing help with my connection string. Can anyone help me with this?
I'm connecting to a database via Oracle SQL Developer. I am able to connect within the UI by providing the following items:
Connection Name - got it.
myUsername - got it.
myPassword - got it.
Connection Type = Basic, Role = default
myHostname - got it.
myPort - got it.
mySID - got it.
However, I am unable to get my connection string to work in VBA. When I run the script I get
"Run-time Error '3076'. Provider cannot be found.
It may not be properly installed" on the line beginning with cnn.open.

Setting Up SqlConnection string in vb.net for a local database created through visual studio 2010

I have been searching for a couple hours, and found several questions, but none of them really explained this in a way I can understand.
I'm programming a game similar to Rock Paper Sissors, except with many more selections, and the possiblity of a tie. I had originally hardcoded all of the possible outcomes, then decided to try a database so I can learn and practice sql as well.
Problem is, I can't figure out for the life of me how to connect to my local database, now that I have set it up and filled it through Visual Studio 2010. I can connect to it through Server Explorer just fine, and I can see it in Solution Explorer. I've tried several things, along the lines of:
Private sqlConn As New SqlConnection("Data Source=(local)|DataDirectory|\Outcomes.sdf;database=Outcomes;Integrated Security=true")
Private sqlConn As New SqlConnection("Data Source=.\SQLEXPRESS; Integrated Security=true")
Dim sqlConn As SqlConnection
sqlConn = New SqlConnection("DataSource=..\..\Outcomes.sdf")
I am relatively new to sql, but know enough through tinkering to build a sql statement and get me the result I want. But I've never connected to a database before. I've looked on MSDN and tried several things I saw on there (everything that looked like what I needed, really) but it still hasn't worked.
If I can connect, I already have my statement set, and have tested it through the database itself. Any help would be wonderful, especially if it's explained in a way I can understand it and use it for later.
Also, if it helps and isn't noticed through my tried code, my db name is Outcomes. I don't know if that is needed or will help, but just in case.
Please visit connection strings here...
It also would have been helpful to know what type of DBMS you are using as well. I noticed you have an .sdf database file, not a DBMS (For ex: MySql, SQL or Oracle). Therefore, your connection string is really going to depend on what you want.
Your issue is here by the way...
Private sqlConn As New SqlConnection("Data Source=(local)|DataDirectory|\Outcomes.sdf;database=Outcomes;Integrated Security=true")
*You cant use the SqlConnection you have because its not supported with the use of .sdf files.
Instead you have to use: System.Data.SqlServerCe 'This is for compact edition
If you would like to know more about this please see here.
Kendra,
Here are the logical Steps you will need to follow to access the database programmatically:
Note: I'm assumming you have the proper SQLExpress | SQL Server Database setup whether local or remote the methods below are identical except for the connection string information.
1) Import the Sql AdoNet Namespace so you can use the proper SQL Server Client Objects & Methods;
a) Imports System.Data.SqlClient
2) Establish a Connection to the database with the ADO Connection Object:
' Create your ADO Connection Object:
Private myConn As SqlConnection
myConn = New SqlConnection("Initial Catalog=OutComes;" & _
"Data Source=localhost;Integrated Security=SSPI;")
Note: This connection string uses integrated security from your windows machine. you could also use standard security where you would need to enter your username and password credentials. Its your choice.
3) Setup Your ADO Command Object to Define your data retrieval query:
'Create a Command object.
Private myCmd As SqlCommand
myCmd = myConn.CreateCommand
myCmd.CommandText = "SELECT FirstName, LastName FROM Employees"
'Open the connection.
myConn.Open()
Note: Subsitute CommandText string for your actual query based upon your own database schema.
4) Read, Fetch, Display Data using the SQLDataReader Object:
Private results As String
Private myReader As SqlDataReader
myReader = myCmd.ExecuteReader()
'Traverse the DataSet and Display in GUi for Example:
Do While myReader.Read()
results = results & myReader.GetString(0) & vbTab & _
myReader.GetString(1) & vbLf
Loop
'Display results.
MsgBox(results)
5) Gracefully Close all Objects Used:
' Close the reader and the database connection.
myReader.Close()
myConn.Close()
Note - You'll need to consult microsoft for further connection string formats, since I don't have enough info. But this should clarify the actual big picture steps for you.
Regards,
Scott

ODBC reading of BMC AR System / Remedy data to VS2010/VB .NET

Edit MY goal is this, I need to do read data from a Remedy Database using a VB .Net app. /Edit
I am trying to read data from the AR System ODBC driver in a VS 2010 VB windows form.
I have added a connection in the data connections via , a system dsn, connection string pulled from a working excel data pull, and built a connection string based via the wizard.
I can test connection, and it comes back 'test connection succeeded'.
When I click ok and the Data connection goes to my server explorer, it expands to tables, view, and procedures and viewing/refreshing those causes errors such as:
Column 'Table_Cat' does not belong to table Tables.
Error [im00][ar system odbc driver] not supported
I am aware there is the api out there, however this has a problem in that the api acts like a login session from the client, which limits you to one login session. This not feasible for the task at hand as the user needs to remain logged into remedy, and the app I'm writing will be read only for data.
The goal is a billboard app that will display certain tickets, kind of like a stock ticker.
There will be no editing of ticket data from remedy, I just need to read the tickets and provide tallies and alerts for our helpdesk.
It seemed so easy when I sat down, but now 4 hours later and a mind numbing amount of irrelevant google results, I'm almost wondering if I'm going to have to report back that it cannot be done with out the api and creating more remedy accounts. Not having to create additional remedy accounts was part of of the request put to me.
Tags: Visual Studio 2010 BMC AR System Remedy ODBC VB.NET
Update
So I have done the code by hand and now seem a few steps forward, but still blind.
Ok, so if i export my excel query it looks like this from the dqy file
export.dqy
DRIVER={AR System ODBC Driver};ARServer=xxxxxx;ARServerPort=xxxxx;UID=xxxx;PWD=xxxx;ARAuthentication=;SERVER=NotTheServer
SELECT "EN:HelpDesk"."Company Name", "EN:HelpDesk"."Call Status", "EN:HelpDesk"."Caller Region", "EN:HelpDesk"."Next Action", "EN:HelpDesk"."Detailed Description(FTS)", "EN:HelpDesk".Device, "EN:HelpDesk"."Submitted-by", "EN:HelpDesk".Impact, "EN:HelpDesk"."Arrival Time", "EN:HelpDesk"."Call Id", "EN:HelpDesk".Market FROM "EN:HelpDesk" "EN:HelpDesk" WHERE ("EN:HelpDesk"."Call Status"<>'Closed') AND ("EN:HelpDesk"."Submitted-by"<>'nis') AND ("EN:HelpDesk".Impact='High') AND ("EN:HelpDesk".Market='DCIN') AND ("EN:HelpDesk"."Caller Region"<>'UK')
First off, these quotes look wrong to me, but it seems to work because if I leave them, executing the command doesn't fail, however it doesn't return data to my data grid view in vb.
Second the EN:Helpdesk looks odd to me but again same results as the quotes.
I have tried changing the quotes to brackets [ ] but receive errors once I do.
Here is my code:
VB Code
Imports SystemM My goal
Imports System.Data
Imports System.Data.Odbc
Imports System.Data.SqlClient
Sub Main()
Dim sql As String
Dim connectionString As String = "DRIVER={AR System ODBC Driver};ARServer=xxx;ARServerPort=xxx;UID=xxx;PWD=xxx;ARAuthentication=;SERVER=NotTheServer"
sql = "SELECT ""EN:HelpDesk"".""Company Name"", ""EN:HelpDesk"".""Call Status"", ""EN:HelpDesk"".""Caller Region"", ""EN:HelpDesk"".""Next Action"", ""EN:HelpDesk"".""Detailed Description(FTS)"", ""EN:HelpDesk"".Device, ""EN:HelpDesk"".""Submitted-by"", ""EN:HelpDesk"".Impact, ""EN:HelpDesk"".""Arrival Time"", ""EN:HelpDesk"".""Call Id"", ""EN:HelpDesk"".Market FROM EN:HelpDesk WHERE (""EN:HelpDesk"".""Call Status""<>'Closed') AND (""EN:HelpDesk"".""Submitted-by""<>'nis') AND (""EN:HelpDesk"".Impact='High') AND (""EN:HelpDesk"".Market='DCIN') AND (""EN:HelpDesk"".""Caller Region""<>'UK')"
Dim bindingSource1 As New BindingSource()
Me.SQLDS_reportresults.DataSource = bindingSource1
Dim myAdapter = New OdbcDataAdapter(sql, connectionString)
Dim commandBuilder As New OdbcCommandBuilder(myAdapter)
Dim table As New DataTable()
table.Locale = System.Globalization.CultureInfo.InvariantCulture
myAdapter.Fill(table)
bindingSource1.DataSource = table
Me.SQLDS_reportresults.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader)
End Sub
Project is a windows forms with a button to activate main(), a textbox (textbox1) and a datagridview(SQLDS_reportresults).
As the code stands, this causes no errors, but my datagridview never populates. Since there are no errors, I'm inclined to think my connection is working , and that my command is being executed,making my problem lay in code, however given the funky use of quotes and en:helpdesk in the sql command, I'm also concerned that is malformed and causing the where portion to return no results.
Anyone have any suggestions / ideas?
I need a way to display these results in app, and right now I don't care how just as long as I can see some data at all.
I've been googling and looked at the vb examples in the api zip but that is not related to opening a odbc connection and I found that of little help in my research.
I almost feel like I'm missing something simple or obvious.
When i run odbcad32.exe my ar system odbc driver shows 7.00.01.02 which is what I assume is installed on everyones machines as I used the remedy install set provided to me by the IT/Software admins to build this dev box.

how to query/get data from Datasource in VB.NET

i am building a database application in vb.net and i started by adding a data source from the DATA in the toolbar. my connection is good and it shows all my tables in the data source panel.
i also see new classes related to my database, like
sakilaDataSet
sakilaDataSet.customerDataTable
...
and so on.
how do i query and use these ? i googled a lot and i am not able to get this.
Dim cust As sakilaDataSet.customerDataTable = New sakilaDataSet.customerDataTable
Dim row() As System.Data.DataRow = cust.Select("customer_id=5")
MsgBox(row.Count)
My last try was with the above code, but the row.count always turns out to be zero.
You need to open a connextion to the DB. Here are some options:
You could use EntityFramework, which provides a nice way to access data and control it by mapping to entities (classes). For this, in VisualStudio create a ClassLibrary project, add an item ADO.NET Entity Data Model. This will open a wizard that will help you connect to the DB, map the objects in the DB to entities and access the entities by a reference to an entity context. The basics are easy.
Other option is to use an OLEDB provider, which is a classic way to access DB. An example to open an Access DB of employees:
Dim connString As String = "provider= microsoft.jet.oledb.4.0; " & _
"data source=Employee.mdb;"
Dim conn As New OleDbConnection(connString)
Try
conn.Open()
Finally
conn.Close()
Console.WriteLine("Connection Closed")
End Try
Visit http://www.connectionstrings.com/ to get a list of common connection string for many DB. Other useful links:
EntityFramework:
http://www.codeguru.com/csharp/csharp/net30/article.php/c15489
http://www.asp.net/entity-framework/tutorials
OLEDB:
http://oreilly.com/catalog/progvbdotnet/chapter/ch08.html
http://www.homeandlearn.co.uk/net/nets12p2ed.html
http://www.sourcecodester.com/tutorials/net/database-programming-made-easy.html
Hope this helps.
What i wanted to achieve was not to use connection strings again. After adding the data source in VB.net, it makes Data Classes and Adapters, which i can use directly to access the database, as follows :
Dim staff As sakilaDataSet.customerDataTable = New sakilaDataSetTableAdapters.customerTableAdapter().GetData
Dim rows() As sakilaDataSet.customerRow = staff.Select("email='" + email.Text + "'")
This website http://visualbasic.about.com/od/usingvbnet/a/begdbapp7.htm had a good tutorial where it talked about what happens when you use the data sources window and how to use it in your code after that.
I know it's an old question, but it was very high in Google results, and it was more of a "This is how you should have done it" answer instead of actually answering with what it seems like you asked

Multiple-step OLE DB operation generated errors

Dim NorthWindOledbConnection As String = "Provider=SQLOLEDB;DataSOurce=SARAN-PC\SQLEXPRESS;Integrated Security=ssp1;InitialCatalog=Sara"
Dim rs As New ADODB.Recordset()
rs.Open("select * from SecUserPassword", NorthWindOledbConnection, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockBatchOptimistic)
i tried to run this above code in visual studio 2008 - it shows the following error:
"Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done"
Firstly, don't use ADO in VB.NET. Use ADO.NET.
Other than that, create a proper Connection object instead of passing around a string.
And fix your connection string. It's SSPI, not SSP1. And it's Data Source, not DataSOurce. And it's Initial Catalog, not InitialCatalog.
You are using a very very very old way to access a Database that has been used with Visual Basic 6 and older.
Check to use ADO.NET instead of old ADO. For example you can use this code that is "similar" to the code you are using (but is not the best way to access the data on VS2008)
OleDbConnection con= New OleDbConnection( **Your Connection String** )
con.Open()
Dim command As OleDbCommand = New OleDbCommand("select * from SecUserPassword", con)
sqlCommand .CommandType = CommandType.Text
Dim reader As OleDbDataReader = TheCommand.ExecuteReader()
While reader.Read()
System.Console.Write(reader(** Your Table Field Name** ).ToString())
End While
con.Close()
To view how to create a correct connection String see the site http://www.connectionstrings.com/
If you want to access to an SQL Server database also you can use the SQLClient namespace instead the OleDb. For example System.Data.SqlClient.SqlConnection instead the OleDbConnection to provide better performance for SQL Server
The link below is an article that gives a great breakdown of the 6 scenarios this error message can occur:
Scenario 1 - Error occurs when trying to insert data into a database
Scenario 2 - Error occurs when trying to open an ADO connection
Scenario 3 - Error occurs inserting data into Access, where a fieldname has a space
Scenario 4 - Error occurs inserting data into Access, when using adLockBatchOptimistic
Scenario 5 - Error occurs inserting data into Access, when using Jet.OLEDB.3.51 or ODBC driver (not Jet.OLEDB.4.0)
Scenario 6 - Error occurs when using a Command object and Parameters
http://www.adopenstatic.com/faq/80040e21.asp
Hope it may help others that may be facing the same issue.