What Provider to use? - vb.net

I am struggling to connect to an SQL database from a VB.NET application using OLEDB. I usually connect to databases using ADO.NET or ODBC for Oracle. The connection string I am using is as follows:
Provider=SQLOLEDB;User ID=myUser;Password=myPassword;Initial Catalog=database;Data Source=server;
The error I get is: "Additional information: Cannot open database 'database' requested by the login. The login failed."
The database, username and password are definitely correct. I have confirmed this by logging onto SQL Studio Manager and connecting to the database successfully.
Therefore it has to be the Provider that is incorrect. I have tried a few different providers e.g. SQLOLEDB.1. How do I find out exactly what provider to use?

Don't bother with OLEDB. Since you're using SQL Server, just use the built-in .NET Framework Data Provider for SQL Server (list of .NET data providers).
In fact, you don't even need to worry about getting the connection string syntax just right. You can use a built-in connection string builder for that too.
Here is some sample code to get you started:
Imports System.Data.SqlClient
// ...
Dim connStringBuilder As SqlConnectionStringBuilder = New SqlConnectionStringBuilder()
connStringBuilder.DataSource = "myservername"
connStringBuilder.UserID = "myusername"
connStringBuilder.Password = "mypassword"
connStringBuilder.InitialCatalog = "mydatabase"
Using conn As SqlConnection = New SqlConnection(connStringBuilder.ToString())
conn.Open()
Using cmd As SqlCommand = New SqlCommand("SELECT mycol FROM MyTable", conn)
Using reader As SqlDataReader = cmd.ExecuteReader()
Do While reader.Read()
Console.WriteLine("Managed to fetch: {0}", reader("mycol"))
Loop
End Using
End Using
End Using

I restarted the server and the connection string issue is resolved. I would delete the question, but there are answers from other users.

Related

Set password for SQLite v3 database

My application uses a database stored in a file available via network. So far, I've been using a MS-Access file (.accdb), but I'm trying to migrate to SQLite Version 3 (.db3).
I added SQLite NuGet package to my project and created a SQLite database using SQLiteStudio. I refactored my database objects to work with System.Data.SQLite.SQLiteConnection instead of System.Data.OleDb.OleDbConnection and it worked well.
However, my previous accdb database was password protected, and I don't know how to apply a password over my current SQLite database.
Can anyone teach me ho to do it? Thanks in advance!
I followed the link which Wudge kindly appointed in comment above, and it works, but I'd rather clarify what need to be done:
To set a password to an unprotected database:
Dim conn = New SQLite.SQLiteConnection(
"Data Source=C:\yourFolder\yourDB.db3;Version=3;")
conn.Open()
conn.ChangePassword("password")
conn.Close()
To open a password-protected database:
Dim conn = New SQLite.SQLiteConnection(
"Data Source=C:\yourFolder\yourDB.db3;Version=3;")
conn.SetPassword("password")
conn.Open()
conn.Close()
or
Dim conn = New SQLite.SQLiteConnection(
"Data Source=C:\yourFolder\yourDB.db3;Version=3;Password=password;")
conn.Open()
conn.Close()
To remove password from a password-protected database:
Dim conn = New SQLite.SQLiteConnection(
"Data Source=C:\yourFolder\yourDB.db3;Version=3;Password=password;")
conn.Open()
conn.ChangePassword(String.Empty)
conn.Close()
PS. The open source database manager SQLiteStudio is able to open files which were password-protected that way, as long as you choose System.Data.SQLite instead of Sqlite 3 as your database type. (Requires v 3.1.1, the current version).

VB 2013 Access DB Dataset

Rewriting a legacy system in VB 2013 Express which connects to an Access DB. I've set up the Data Connection and have a DataSet with all the tables. The code needs to do the following:
Delete all the rows in the "extract" table;
Read in and parse the new data;
Write the new data to the "extract" table.
I've got the reading and parsing part done, but I need help with the deleting and writing part. Nothing I try seems to work.
This is what i've tried:
Dim sqlConnection1 As New System.Data.SqlClient.SqlConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\CLI_CRVM.accdb")
Dim cmd As New System.Data.SqlClient.SqlCommand()
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "DELETE FROM extract"
cmd.Connection = sqlConnection1
You are trying to use System.Data.SqlClient, but that is specifically for working with Microsoft SQL Server databases. The example code in your question will fail with
Keyword not supported: 'provider'.
For an OLEDB connection to your Access database, use System.Data.OleDb.

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

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.

ADO.Net Synchronization & SQL CE

I've succesfully synchronized both source and local db using the local database cache item in VS 2008.
However, I need to access the SQL CE db directly from within another dll/process, and without using a dataset. The reason being that my business object code does not use datasets.
The final code wouldlook something like this:
Dim conn As New SqlServerCe.SqlCeConnection("Data Source=C:\Development\UserDirectory\UserDirectory.DBSyncher\ProfDir.sdf;Persist Security Info=False;")
Dim cmd As New SqlServerCe.SqlCeCommand("Select EmailAddress from Employees Where ID=23", conn)
Dim returnString As String = ""
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
returnString = cmd.ExecuteScalar
conn.Close()
cmd = Nothing
I notice something very strange using a dataset the synchronized changes are shown but accessing the CE database file directly returns old data - no synched data whatsoever.
What am I missing? Any help would be greatly appreciated.
Figured it out!
Forgot that CE is in process, thus it copies the database file(.sdf) to the Debug folder. You have to to reference that database not the one in your project. DOH!