How to connect to SQL Server redundantly using C#? - 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)

Related

how to connect a single SQL server database to two different C# WPF applications over the network

i am developing an app where i am having a common sql server database .mdf put on a LAN Server which is needed to be connected to two or more different instances of a same application as other stations.
i am able to select the database but it is giving me and error posted below:
how to overcome this? the connection string is
connectionString = #"Data Source =(LocalDB)\MSSQLLocalDB; AttachDbFilename = " + path + "; Integrated Security = True; Connect Timeout = 30";
P.S. it is working when a single instance is connected to it and it is preventing the second or third app to use it.
any help will be appreciated.
You need to host the database on a network server. Several clients can connect to a SQL Server. But several clients cannot simultaneously connect directly to an MDF file.
The file alone cannot handle the concurrency. You need to have an application for it. That's where SQL Server comes into play.
After hosting, you need to change your connection string as well. Then it should work.
connectionString="Data Source=ServerName;Initial Catalog=DatabaseName;Integrated Security=True;MultipleActiveResultSets=True"

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.

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.

SQL Server Connection Timeout C#

First off I'd like to let everyone know I have searched my particular problem and can't seem to find what's causing my problem.
I have an SQL Server 2008 instance running on a network machine and a client I have written connecting to it.
To connect I have a small segment of code that establishes a connection to an sql server 2008 instance and returns a DataTable populated with the results of whatever query I run against the server, all pretty standard stuff really. Anyway the issue is, whenever I open my program and call this method, upon the first call to my method, regardless as to what I've set my Connection Timeout value as in the connection string, it takes about 15 seconds and then times out. Bizarrely though the second or third call I make to the method will work without a problem.
I have opened up the ports for SQL Server on the server machine as outlined in this article: How to Open firewall ports for SQL Server and verified that it is correctly configured. Can anyone see a particular problem in my code?
string _connectionString = "Server=" + #Properties.Settings.Default.sqlServer + "; Initial Catalog=" + #Properties.Settings.Default.sqlInitialCatalog +
";User Id=" + #Properties.Settings.Default.sqlUsername + ";Password=" + #Properties.Settings.Default.sqlPassword + "; Connection Timeout=1";
private DataTable ExecuteSqlStatement(string command)
{
using (SqlConnection conn = new SqlConnection(_connectionString))
{
try
{
conn.Open();
using (SqlDataAdapter adaptor = new SqlDataAdapter(command, conn))
{
DataTable table = new DataTable();
adaptor.Fill(table);
return table;
}
}
catch (SqlException e)
{
throw e;
}
}
}
The SqlException that is caught at my catch is : "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding."
This occurs at the conn.Open(); line in the code snippet I have included. If anyone has any ideas that'd be great!
Addendum If I ping the server it's <10ms response time. Additionally I'm getting the same behavior when using SQL Server Management studio (I've just tried this after writing this question as the thought just crossed my mind). I would presume that this has to be a network issue as opposed to a code issue as it also takes two attempts when using SQL Server Management studio. I realise I can implement an error check for connection failure and then re-attempt the connection (I should probably do this anyway) but this doesn't seem particularly 'clean' to me as it doesn't address the underlying problem. Does anyone here have any experience with this issue?
Edit
Although over a year later this question has been viewed over 4000 times, I've since discovered that although I /thought/ the firewall ports were opened, they actually weren't. I'd incorrectly assumed that you need to open the firewall in Windows to the port number that SQL Server uses, in my case I set it to allow connections on TCP port 1433, the firewall caused issues when attempting to establish an initial connection.
I discovered that the correct way to set it up was to set Windows Firewall to allow the SQL Server Instance executable through. To do this you need Add a Program in Windows Firewall, browse to the folder your sql instance resides in such as C:\Program Files (x86)\Microsoft SQL Server\MSSQL10_50.SQLINSTANCE\MSSQL\Binn and then add the sqlservr.exe file to the firewall rules.
You are setting the connection timeout value to 1 second. Drop it from connection string and try again.
Or the problem could be with the SQL select you are using. Could it be taking a long time. If so, the 2nd and 3rd calls would retrieve the cached values and thus run much quicker.

SQL Server connection count issue

I am using SQL Server 2008 Enterprise + .Net 3.5 + C# + ADO.Net. I am using the following SQL statement to monitor connection number, is it correct? If yes, my confusion is, one connection from ADO.Net client maps to only one connection in the following statement? Or one ADO.Net connection could maps to multiple connections here?
SELECT * FROM sys.dm_os_performance_counters WHERE object_name = 'SQLServer:General Statistics'
(Monitor User Connections row)
thanks in advance,
George
Use SELECT * FROM sys.dm_exec_connections to find all the connections. The client_net_address has the client address so you can track down the origin of connections.
Use SELECT * FROM sys.dm_exec_sessions to find all the sessions (sessions in general map 1 to 1 with connections unless MARS is used). The program_name column will contain the value of the application name you passed in in the connection string and allows you to identify your own connections.
Use SELECT * FROM sys.dm_exec_requests to see all the current executing batches (requests).
The performance counter would only give you one value, the number of current connections:
SELECT cntr_value
FROM sys.dm_os_performance_counters
WHERE object_name = 'SQLServer:General Statistics'
and counter_name = 'User Connections'
Would this work for your needs? I'm confused if you're trying to count the number of connections. Your question seems to say no, where your comment implies yes to me.
Sp_who2 'Active'
By default, the underlying SQL Server driver code uses a connection pool. You'll find that the number of physical connections "owned" by your application will grow over time to the current limit, but this is different from the number that are "in use".
This avoids renegotiating security, etc. on each link, speeding up your application's database access.
As mentioned by #sgmarshall, use the sp_who2 stored procedure to determine what each of the connections are currently doing.

Categories