connect to database c# - 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.

Related

Connect desktop c# application to online mySql databse

I have a windows form application in C# and sometimes I want to push some data table from this application to an online mySql server which is hosting all data for my website in PHP. To do that I've installed :
1- MySql for visual studio version 1.2.3
2- MySql Connector.Net 6.9
Also, I have enabled Remote MySql on the server so I can make the connection. I used the '%' wildcard for the meantime because my IP address is dynamic.
my basic c# connection code is as below :
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
myConnectionString = "Server=*******;Database=*******;Uid=******;Pwd=********;";
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = myConnectionString;
conn.Open();
MessageBox.Show("connected successfully..");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
Unfortunately, every time I run this code I am getting an error which says
"Unable to connect to any of the specified MySQL hosts".
I don't' know where the problem is. Is it something on the UNIX server which
blocks the connections or some other thing which I need to do. I am also new to the CPanel interface and how to deal with it.
I appreciate all the help provided.
Many Thanks.
http://www.codeproject.com/Articles/43438/Connect-C-to-MySQL
Did you see that? You can try it.
I know this is an old question but I had the same issue many years ago and the only way I could get it to work was to enable remote MySql on the server I was running. This basically means allowing remote connections to access the DB. This of course is very risky and poses a major security problem. You can limit connections from specific IPs, but in my opinion its best to have a local DB and then perhaps push updates to an online source somehow.

How connect C# to Postgresql in host j.layershift.co.uk

I have installed postgresql database in http://postgres-project-1241043.j.layershift.co.uk/ host.
I want to connect to the database using C#. I use Npgsql with following connection string.
connectionString = # "Server = postgres-project-1241043.j.layershift.co.uk, Port = 5432, User Id = postgre; Password = abcdef; Database = dbluanvantn;";
But I am not able to connect to the server and get error:
Npgsql.NpgsqlException: Failed to a connection to
'postgres-project1241043.j.layershift.co.uk'.
Am I using correct connection string?. Help me fix it.
You can only connect to Postgres (on our Jelastic service) if you add a public IP to the node first. Without that step, you can only connect to it locally (i.e. from another server within your Jelastic environment).
Also I want to mention that you are always welcome to contact our support team (our tech. support is 24x7 and completely free; even for our trial accounts) if you need any further help.

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.

connect mysql with c#

I'm building a c# windows application which will connect with the mysql database in a remote server.
I'm using the following connect script
string connectionString;
connectionString = "SERVER = eu5.org;UID = myuserid; PASSWORD = mypassword; DATABASE = mydatabasename;";
connection = new MySqlConnection(connectionString);
It shows the error couldn't connect to the database.
P.S: Mysql database is at eu5.org server
Personally I prefer to use the MySql Workbench IDE for testing connections and working (Querying) the database directly where possible. Most hosted databases that I have worked with normally define the Server as Instance.[DomainName] so I would have expected your server URL to be something like MySql1.eu5.org
Below is a connection string that I tested using the MySql Connector, change the parameters.
<connectionStrings>
<add name="MySqlConnection" connectionString="server=INSTANCENAME.DOMAINNAME.COM;UID=USERNAME;password=PASSWORD;database=DATABASENAME;Persist Security Info=True;" providerName="MySql.Data.MySqlClient"/>
MAke sure that your server should be started...
Just read the FAQ:
Many people want to only use database, but their site is hosted elsewhere. We provide free database for websites hosted with us. For that reason, external access is blocked without exception.
--> http://www.freewebhostingarea.com/faq.html
so it's not possible to access your MySQL-DB from external sources.
only localhost will be allowed
Your code is correct.
Use a browser for MySQL, like http://mysql-query-browser-for-windows.apponic.com/ to check if your database is available.

How to connect to SQL Server redundantly using C#?

I have two SQL Server machines, server1 and server2 that are redundant and have the same data.
My application wants to select data from a table in the msdb database every 1 second. But my application can connect only using one conection string. How to edit my application can work redudantly with both servers?
SQL Server 2000 SP4
Window Server 2003
C#
My connection string is
server=10.15.13.70;database=msdb;user id=sa;pwd=""
Please advise me.
Pick a server at random and insert the name or IP for that in the connection string before opening the connection.
using (SqlConnection _con = new SqlConnection("server=" + giveMeAServer() + ";database=msdb;user id=sa;pwd="))
and:
private String giveMeAServer()
{
return "10.15.13.70";
}
The proper fix, especially if you are reconnecting as often as once per second, is most likely to set up some sort of cluster on the SQL Server side, and connect to that, rather than having your application worry about load balancing the database backend.
Better is you try to open the connection for some interval say 5ms, and if connection cant be opened, switch to other server through connection string
What you are looking for is Load balancing. This is a technique that can only be applied to readonly databases. It basically spreads the load across multiple servers.
Here is a good read on load balancing with SQL Server 2000 by Microsoft.
http://technet.microsoft.com/en-us/library/cc917707.aspx
Imho, what you try to achieve should not be handled programmatically but on a hardware level.
Data Source=myServerAddress;Failover Partner=myMirrorServerAddress;Initial Catalog=myDataBase;Integrated Security=True;
(from http://www.mssqltips.com/tip.asp?tip=1289)

Categories