OleDB connection string for SQL Server in a C# program - c#

I have seen lots of answers to connect to MS Access via OleDB but there is not good answer for SQL Server. I try to connect to a SQL Server database via OleDB provider in my C# program.
This is the connection string I am providing.
Provider=SQLOLEDB;Data Source=<servername>;Initial Catalog=<dbname>;Integrated Security=SSPI
But it gives me error
‘Keyword not support ‘Provider’’
What I want to do here is connect database via OleDB in C# program.

This works as expected on my side. From the error message I strongly suspect that you are using the SqlConnection class instead of the OleDbConnection (Of course you need to use all the other classes provided by OleDb like OleDbCommand, OleDbDataReader etc...)
string connStr = "Provider=SQLOLEDB;Data Source=<servername>;Initial Catalog=<dbname>;Integrated Security=SSPI";
using(OleDbConnection cnn = new OleDbConnection(connStr))
{
....
}

When in doubt, use the string builder in visual studio. That way unsupported keywords can't creep into your connection strings, the following is a wonderful example on how to use it.
http://www.c-sharpcorner.com/uploadfile/suthish_nair/how-to-generate-or-find-connection-string-from-visual-studio/

The same Connection string is working fine at my end.
I am posting my sample code which is executes successfully at my end
public string connStr = "Provider=SQLOLEDB;Data Source=.;Initial Catalog=<dbName>;Integrated Security=SSPI";
public OleDbConnection con;
protected void Page_Load(object sender, EventArgs e)
{
Test();
}
public void Test()
{
con = new OleDbConnection(connStr);
con.Open();
OleDbCommand cmd = new OleDbCommand("select * from tblApartments", con);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
}
Please place breakpoint and check line to line and when your breakpoint comes to con.close(); then check ds, you can see the output.

The connection string you're using, considering the OLE DB provider, is correct. I didn't find any error in the connection string used, if you want to connect to a SQL Server data source.
Most probably, the reason of that error should be that you're not using correctly all the classes and objects required by the OLE DB provider, like OleDbCommand (that is similar to a SqlCommand but it's different), OleDbConnection, OleDbDataAdapter and so on. In a nutshell, the reason of that error should be this:
string connStr = "Provider=SQLOLEDB;Data Source=<servername>;Initial Catalog=<dbname>;Integrated Security=SSPI";
using(SqlConnection scn = new SqlConnection(connStr))
{
....
}
Indeed, using a SqlConnection object, the ConnectionString property doesn't support the keyword Provider and, executing your application, you got an error about a keyword not supported.
Have a look at this simple tutorial about the use of OLE DB provider.

Related

Could not find available ISAM

OleDbConnection connect = new OleDbConnection ("Provider=Microsoft.ACE.OLEDB.12.0;Data source:C:\\Users\\PC\\Documents\\Visual Studio 2013\\Projects\\WindowsFormsApplication1\\WindowsFormsApplication1\\Firebird damagem0.accdb;Persist Security Info=False");
public partial class Form3 : Form
{
// OleDbconnection database
OleDbConnection connect = new OleDbConnection ("Provider=Microsoft.ACE.OLEDB.12.0;Data source:C:\\Users\\PC\\Documents\\Visual Studio 2013\\Projects\\WindowsFormsApplication1\\WindowsFormsApplication1\\Firebird damagem0.accdb;Persist Security Info=False");
public Form3()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// Set up command
connect.Open();
OleDbConnection command = new OleDbConnection("SELECT [Damage columns], ID FROM [Copy of Firebird m0 damage]; connection");
command.ExecuteNonQuery();
DataTable ds = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter (command);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox3.Items.Add(dr["[Damage columns]"].ToString());
}
connect.Close();
}
Error occurs at connect.Open(); I've done everything right but i still keep receiving the error, any suggestions?
This error is typically due to an invalid connection string.
Since you have a space in your datasource path, try wrapping it with single quotes. Also, it should be
Data Source=
not
Data Source:
You connection string looks to be wrong with a semicolon after Data Source.
OleDbConnection connect = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data source=C:\Users\PC\Documents\Visual Studio 2013\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Firebird damagem0.accdb;Persist Security Info=False");
Also you have another OleDbConnection there in code which should be OleDbCommand.
And finally, did you install the access database engine?
I just managed to produce a very similar error out of thin air (it worked before) and after a while of digging around what I changed since then I finally found the mistake:
Provider=Microsoft.Jet.OleDb.4.0;Data Source=myfile.mdb
works, while
Provider=Microsoft.Jet.OleDb.4.0;DataSource=myfile.mdb
produces
Installable ISAM not found
For those who don't see it: The difference is the spelling of the key Data Source vs DataSource - the space character is important here!

Could not open a connection to SQL Server 2012

Hy,
I am using SQL Server 2012 under MS Visual Studio 2012.
Below is my connection string from app.config
<add key="Platform" value="Data Source=Bigfoot2;Initial Catalog=Platform;Integrated Security=True"/>
and my connection class
static SqlConnection con;
public static SqlConnection GetConnection()
{
con = new SqlConnection(ConfigurationManager.AppSettings["Platform"].ToString());
return con;
}
internal void AddCustomer (Buyer customer, User user, PlatformType type )
{
SqlConnection conn = DALConnection.GetConnection();
try
{
SqlCommand cmd = new SqlCommand("InsertCustomer", conn);
cmd.CommandType = CommandType.StoredProcedure;
...
con.Open();
cmd.ExecuteNonQuery();
My database is stored under my project folder.
The error I get when I try to use my method is:
Could not open a connection to SQL Server 2012
Sincerely,
Your connection object is wrong, you are passing conn in Command while for Connection open you are using con object not conn:
con.Open();
use :
conn.Open();
you code will be like:
try
{
SqlCommand cmd = new SqlCommand("InsertCustomer", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
cmd.ExecuteNonQuery();
}
Although your code has some issues, It seems that it should work.
Try testing your connection string using an independent tool for connectivity.
For testing the connection string take a look at this SO thread.
As #hvd has mentioned in one of the comments, your code is confusing as you have con which is equivalent to conn. this makes your code hard to follow. I recommend you refactor it so it will be easier for you (and others) to follow.
Good luck!
Try this:
<add key="Platform" value="Data Source=.\Bigfoot2;Initial Catalog=Platform;Integrated Security=True"/>
If your SQL Server is on a different machine than your Visual Studio or app, are the required ports open in the Windows Firewall ?
Try these steps:
http://blog.sujay.sarma.in/2013/12/19/SCRIPT-Open-ports-in-Windows-Firewall-for-SQL-Server-connectivity

How to central the db connection in c# .net?

Does anyone know how can I central the db connection in c# .net (perhaps in the mian.master)?
I have the following code for the db connection and used to call to the difference stored proc to retrieved data.
string strConnString = ConfigurationManager.ConnectionStrings["testString"].ConnectionString;
SqlConnection mySqlConnection = new SqlConnection(strConnString);
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText = "EXEC app_campaign_select #CampaignID=" + Request.QueryString["ixCampaign"].ToString();
mySqlConnection.Open();
SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
Instead of coding it in every pages and connection to the db multiple times, any way I can code the following connection code in the master page and only connecting to the db once, then each page can call it when need to be connect into the db
string strConnString = ConfigurationManager.ConnectionStrings["testString"].ConnectionString;
SqlConnection mySqlConnection = new SqlConnection(strConnString);
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
SqlDataReader mySqlDataReader;
Add it to a static DAL class and add parameters as needed.
public static void YourFunction() {
// your code
}
Note:
Beware this line: mySqlCommand.CommandText = "EXEC app_campaign_select #CampaignID=" + Request.QueryString["ixCampaign"].ToString();
If that QueryString comes from a user entered value somewhere, you could be open to SQL Injection.
Sure. Just create a helper class that has a few static methods in them for each type of return type you could have. Pass to one a string for stored procedure name and have an overloaded one that takes a string for a sql statment that you would pass in. You can also have one that just returns back a scalar value as well. So you would probably have 3 or so static methods you could call from any page.

Error While Adding DataSource in Data Connections

When I tried to add a connection it is showing the following error as shown in the attachment. “Unable to open the physical file. Access is Denied” .
When I searched about it, it suggest for adding the SQL Server’s account to the folder. Then, using the following query I found that the account is “LocalSystem”. When I tried to add “LocalSystem” to ACL of the folder, such an account is not available. How do we resolve it and add the connection to DBML?
Note: When I used DataReader with the database name in a C# program, it worked well.
Query Used:
declare #sqlser varchar(20)
EXEC master..xp_regread #rootkey='HKEY_LOCAL_MACHINE',
#key='SYSTEM\CurrentControlSet\Services\MSSQLSERVER',
#value_name='objectname', #value=#sqlser OUTPUT
SELECT convert(varchar(30),#sqlser)
Working C# Program:
SqlDataReader rdr = null;
SqlConnection con = null;
SqlCommand cmd = null;
try
{
// Open connection to the database
string ConnectionString = "server=D088DTRV;integrated security=true; database=BankAccount";
con = new SqlConnection(ConnectionString);
con.Open();
string CommandText = "SELECT * FROM Account";
cmd = new SqlCommand(CommandText);
cmd.Connection = con;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string test = rdr["AccountType"].ToString();
}
}
The problem was related to Data Connections.
In the advanced window, when I checked, it was trying for ./SQLExpress. I modified it with ".".
I restarted the machine. I also stopped the SQLExpress in the services.msc
Data Source=.;AttachDbFilename=C:\DevTEST\Databases\LibraryReservationSystem.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True

is there anyway to connect to sybase from c# without having to add a ODBC DSN connection in control panel

I am looking for a way to connect to sybase from C# without having to setup an ODBC DSN connection locally on the machine.
Is this possible? I tried all of these different connection strings:
static private DataTable Run(string sql)
{
var conn = new OdbcConnection();
const string CONN_STRING2 =
"Data Source='[myServer]';Port=5020;Database=[dbName];Uid=[user];Pwd=[pwd];";
const string CONN_STRING1 =
"Provider=Sybase.ASEOLEDBProvider.2;Server Name=[myServer];Server Port Address=5020;Initial Catalog=[dbName];User ID=[user];Password=[pwd];";
conn.Open();
var da = new OdbcDataAdapter { SelectCommand = conn.CreateCommand() };
da.SelectCommand.CommandText = sql;
var dt = new DataTable();
da.Fill(dt);
da.Dispose();
conn.Close();
return dt;
}
But I got an error stating:
{"ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified"}
You are using var conn = new OdbcConnection(). That is why you are getting the error.
You will need to use a sybase oledb client library. I don't know sybase at all but last I heard one needed to purchase a third-party provider. This was almost three years ago so they may have one by now.
You would then need to do something like var connection = new ASEConnection().
Download the DLL from the following link:
Sybase library
Use this library for connection:
ASEconnection connection = new AseConnection();
Use specific ADO.Net data provider stright from manufacturer (SAP now own sybase). I think you can manage to create a connection string yourself using this reference. For example:
var connStr = #"Data Source=\\myserver\myvolume\mypat\mydd.add;User ID=myUsername;
Password=myPassword;ServerType=REMOTE;"
using (ASEConnection conn = new AseConnection(connStr)) {
// use conn
}
Same informaton can be obtained from documentation mentioned earlier.

Categories