C# connect to System ODBC datasource - c#

The server admin created a 32-bit ODBC system DSN for me that has the database and user credentials in it. I'm struggling now to understand how to connect to that database from my C# code. If I'm using an SSIS connection it goes through without issue, so I know the data they set is correct.
Am I supposed to be using SqlConnection or OleDbConnection to access this now? I've tried both, and no matter what type of connection strings I try it always results in errors. This is connecting to a Denodo instance of that matters for the connection string.

Just put in the DSN name that's been configured:
using System.Data.Odbc;
OdbcConnection DbConnection = new OdbcConnection("DSN=SAMPLE_ISAM");
// Your code here
DbConnection.Close();
Everything else is the same, the "Connection String" information is all contained in the DSN itself, if properly configured.

Related

C# Oracle Connectionstring

I've got a little problem between oracle and C#. I can't seem to connect to my database(=localhost) within my application. I'm using Oracle XE11.2. The error occurs everytime I'm calling "conn.Open()" and Oracle returns this error: {"ORA-12154: TNS:could not resolve the connect identifier specified"}.
I'm 100% sure that the User Id and the Password are correct because I can login to the database via SQL Developer. I think the problem might be in the data source but I'm not sure. Anyone who can help out?
Here is my code:
string connstring = "Data Source=xe;User Id=Software;Password=Software";
//Open connection
OracleConnection conn = new OracleConnection(connstring);
conn.Open();
Did you try tns ping "tnsping xe" from the machine where you are running your program?

connect to database c#

I'm trying to connect to a DB on a server using C# but with no luck.
I tried using this:
public static string m_ConnectionString =
#"Network Library=dbmssocn; Data Source=*server ip*,*port*; database=*db name*; " +
#"User id=*db username*; Password=*db pass*;";
public static SqlConnection myConnection = new SqlConnection(m_ConnectionString);
I get this error:
Connection Timeout Expired. The timeout period elapsed while
attempting to consume the pre-login handshake acknowledgement. This
could be because the pre-login handshake failed or the server was
unable to respond back in time. The duration spent while attempting
to connect to this server was - [Pre-Login] initialization=9343;
handshake=5654;
when I used myConnection.Open();
I tried also to set the timeout to int.MaxValue and it didn't work.
A very good source for SQL Server (and many other) connection strings is http://www.connectionstrings.com/sql-server/. Depending whether you are connecting through ODBC, OLE DB or Native Client, you have to choose another connection string.
Try
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
or
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
There are a lot of options to choose from, depending on the exact SQL Server version, the security type and many more.
UPDATE
First you have to choose a data access technology.
.NET Framework Data Provider for SQL Server (SqlConnection), Is the preferred way of accessing the SQL Server from .NET code. (See When to use the SQL Native Client for a comparison)
Native Client: Is a very fast way of accessing the SQL Server and supports the new features, as it accesses the SQL Server TDS protocol directly and works for non .NET code. It should be preferred for non .NET code.
ODBC: Is relatively fast and compatible to a lot of different databases. Choose this one if the data base type might change in future or if you are accessing "exotic" databases.
OLEDB: For SQL Server it is relatively slow and will be depreciated by Microsoft.
Then you have to choose between SQL Server Authentication (User/Password) and Windows Authentication. I would choose the latter if possible. With Windows Authentication the SQL-Server assumes that if you logged in successfully to Windows you are a trusted user. The Windows user name will then be mapped 1 to 1 to a SQL-Server user. Of course this user then must still have been granted the rights requested for the operations that he will perform on the SQL Server (like SELECT, INSERT, UPDATE, DELETE). If the DBA didn't install Windows Authentication, you will have to go with uid/pwd.
This worked for me:
string connectionString =
"Data Source=192.168.123.45;Initial Catalog=MyDatabase;Integrated Security=SSPI;";
using (SqlConnection connection = new SqlConnection(connectionString)) {
using (SqlCommand command = new SqlCommand(
"SELECT Region FROM dbo.tlkpRegion WHERE RegionID=30", connection)) {
connection.Open();
string result = (string)command.ExecuteScalar();
MessageBox.Show("Region = " + result);
}
}
I think that Data Source=*server ip*,*port*; should be Data Source=*server ip*:*port*;, replacing , with :. But if the port is not specific, I don't think you really need it. Also you're not defining a driver, I don't know it this works without it.
Also a advice: look up LINQ to SQL or ADO.NET Entity Data Model. Those can really simplify use of databases and using LINQ you can write a query inside code which is a lot similar to sql and Visual Studio also helps with intellisense so you don't have to remember all table and column names.

Connection string works for OLE DB connection but not Sql Server Native Client 10.0

The following is a connection string generated when I connect to a database using a configuration tool with Microsoft OLE DB Provider for SQL Server.
Provider=SQLOLEDB.1;Password=password;Persist Security Info=True;User ID=sa;
Initial Catalog=database;Data Source=localhost;Use Procedure for Prepare=1;
Auto Translate=True;Packet Size=4096;Workstation ID=computer1;
Use Encryption for Data=False;Tag with column collation when possible=False
If I connect to the same database but with SQL Server Native Client 10.0 I get this connection string.
Provider=SQLNCLI10.1;Integrated Security=\"\";Persist Security Info=False;
User ID=sa;Initial Catalog=database;Data Source=localhost;Use Procedure for Prepare=1;
Auto Translate=True;Packet Size=4096;Workstation ID=computer1;
Initial File Name=\"\";Use Encryption for Data=False;
Tag with column collation when possible=False;
MARS Connection=False;DataTypeCompatibility=0;Trust Server Certificate=False\0
I have a c# application that reads either one of these connection strings and uses it to create a connection to my database like so
SqlConnectionStringBuilder _sqlConnectionStringBuilder = new SqlConnectionStringBuilder();
OleDbConnectionStringBuilder conBuilder = new OleDbConnectionStringBuilder( CONNECTION STRING SHOWN ABOVE);
_initialCatalogValue = (string)conBuilder["Initial Catalog"];
_dataSourceValue = conBuilder.DataSource;
_sqlConnectionStringBuilder.Password = (string)conBuilder["Password"];
_sqlConnectionStringBuilder.UserID = (string)conBuilder["User Id"];
_sqlConnectionStringBuilder.InitialCatalog = _initialCatalogValue;
_sqlConnectionStringBuilder.DataSource = _dataSourceValue;
_sqlConnectionStringBuilder.PersistSecurityInfo = true;
_conn = new SqlConnection(_sqlConnectionStringBuilder.ConnectionString);
_conn.Open();
The problem that when I use the SQL Server native client the password is empty and my SQLConnection will fail on the login. The error I get is "Login failed for user 'sa'".
The OLE DB connection string is successful. Is my login failing for the sql server native client due to some of the classes I am using in c#? Does the Sql Server Native Client 10.0 encrypt the password? Should I try to identify which provider is in the connection string and have two different code paths? If so what would it take to connect?
Basic question is, how can I ensure a successful connection regardless of which connection string I receive (only the two above)?
N.B. I have no control over the connection strings. I can only work with what I am receiving.
The second connection string you provide does not include a password; thus conBuilder["Password"] returns an empty string when you set conBuilder.ConnectionString to the second string.
The problem was solved as follows.
There was a main application that was making use of the above connection strings and was doing the following.
The application would take the connection string.
If the connection string's provider is SQL Server Native Client (SQLNCLI10.1) the application checks for persistent security. If it cannot find any it adds IntegratedSecurity=SSPI to the connection string and then connects using windows authentication instead. Whether or not this is the right (or secure thing to do) that is what was being done.
To 'answer' the question. You can take in the connection string and if you do not find a password you can set IntegratedSecurity=SSPI. This will allow you to connect using windows authentication instead of SQL Server authentication. I am not advising that you do, but it will work.

Error connecting to Amazon EC2 MySQL from C#

I have an AWS EC2 instance running. I've tried to make a connection to my MySQL like this in C#
MySqlConnection l_DBConn = new MySqlConnection();
l_DBConn.ConnectionString = "Server=my-ec2.compute-1.amazonaws.com;Port=3306;Database=mydatabase;uid=root;password=mypassword;port=3306;charset=utf8"
MySqlCommand command = l_DBConn.CreateCommand();
command.CommandText = "select * from users";
MySqlDataReader Reader = command.ExecuteReader();
The error received when I run the last line is "Connection must be valid and open.". I still can connect to my instance using Filezilla,Putty and MySQL WorkBench also(with SSH). And I'm using MySql.Data.MySqlClient in my code. Anyone has any idea about this? Is this because my instance does not allow remote access or a problem with my connection string?
Thank you in advance,
Wayne.
Edit: The problem is solved by adding l_DBConn.Open() and add my IP to the server using RANT ALL PRIVILEGES ON . TO root#'hostname' IDENTIFIED BY 'root-password'. Thanks!
Try calling l_DBConn.open() before executing the reader. The error implies that the connection is not open since you haven't explicitely opened it
Some ideas:
Make sure you can connect to your database locally first.
Is Sql Server setup to allow mixed authentication
Have you open port 3306 in the EC2 firewall and the windows firewall if you're running it.

Can't connect to Oracle using Windows Authentication with ODP.NET

I've configured my Oracle Database for NTS Authentication and set my Windows Login up as a user in the database.
I'm able to log in to the Database with the command sqlplus /.
I'm also able to connect using Windows Authentication using the System.Data.OracleClient provider for ADO.NET.
For example, the following code snippet works:
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OracleClient");
DbConnection connection = factory.CreateConnection();
connection.ConnectionString = "Data Source=//localhost/Test; Integrated Security=yes";
connection.Open();
However, I'm unable to connect using Windows Authentication using Oracle.DataAccess.Client (ODP.NET).
DbProviderFactory factory = DbProviderFactories.GetFactory("Oracle.DataAccess.Client");
DbConnection connection = factory.CreateConnection();
connection.ConnectionString = "Data Source=//localhost/Test; User Id=/";
connection.Open();
This block of code results in the following exception:
Oracle.DataAccess.Client.OracleException was unhandled
Message=ORA-1017: invalid username/password; logon denied
According to this link I should be able to create an ODP.NET connection to Oracle using the provided connection string: http://www.oracle.com/technetwork/articles/dotnet/cook-masteringdotnet-090821.html
Why does the ODP.NET client not allow me to connect while the (deprecated) Microsoft client does?
This problem was discussed at the following thread in 2007, but no solution was every provided: http://forums.oracle.com/forums/thread.jspa?messageID=2312148.
This is a showstopper.
It works fine for me using ODP.net 11 and this connection string (with a tnsnames.ora file in the Oracle client to define DLGP): Data Source=DLGP;User Id=/;Password=;
Your sqnet.ora file needs to be setup correctly for this to work, but that should already be the case if SQLPlus can connect. Do you only have one Oracle home? If ODP.net is picking up a second one that can muck things up nicely (and that can happen depending on how you install it).

Categories