Application keep old sql connection when switch database (C#) - c#

I have two SQL Server databases, server name are sql1 and sql2.
When I switch database from sql1 to sql2 (using HaProxy), my application still keeps the old SQL connection to server sql1.
However, other applications (using Linq-to-SQL) can get the new SQL connection to sql2.
Please see my code below that's I using to get connection to SQL Server:
using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString))
{
using (SqlCommand command = new SqlCommand())
{
conn.Open();
//do something...
conn.Close();
return data;
}
}
What's my problem? How can I resolve this? Thanks!

You need to know the HAProxy listen configuration, maybe your HAProxy has exceptions programmed, or the redirection only works if you use an specific IP address destination or come from an specific IP range. Please compare the connections string used in each case.
https://www.stevefenton.co.uk/2016/11/load-balancing-microsoft-sql-server-with-haproxy/

Related

Inner Join two databases to import data - SQL C#

I've created a Winforms app in C#. I do have both my Datasources listed as Datasets.
LOTSDataSet = Source Info
webbitdbdataset = Destination Dataset.
These are connected with LOTSConnectionString and WebbitConnectionString.
Anyway I have the code shown below that I am getting a connection error on, when I try to import data from LOTS to Webbit.
SqlConnection lotscon = new SqlConnection(PackChecker.Properties.Settings.Default["LOTSConnectionString"].ToString());
using (OleDbConnection con = new OleDbConnection(PackChecker.Properties.Settings.Default["WebbitConnectionString"].ToString()))
{
string strgetloc = #"INSERT INTO tblinstitution (
dispenseinstid, institutionname )
SELECT NEWinstitution.institutionid, NEWinstitution.institutionname
FROM NEWinstitution LEFT JOIN tblinstitution ON NEWinstitution.institutionid
= tblinstitution.dispenseinstid
WHERE (((tblinstitution.institutionid) Is Null));";
using (OleDbCommand cmd = new OleDbCommand(strgetloc, con))
{
lotscon.Open();
con.Open();
cmd.ExecuteNonQuery();
con.Close();
lotscon.Close();
}
}
Trying to "OPEN CONNECTION" for both connections was just something I tried.. I guess knowing it was going to fail, but I wanted to try before I asked on here.
The command is attached to the OLEDB connection to Webbit, thus I'm getting an exception based on 'cannot find LOTS server'
Prior to running the query I do run a connection checker, which opens both connections and "tries and catches" both connections to make sure they are valid connections.
Using Access the query does work, so I know the issue 100% is trying to open these connections to two databases!
Any direction would be appreciated.
Gangel

Problems connecting to a local MySQL database using C# and .NET 2.0

Newb questions incoming.
I'm running MySQL locally and I am having a really hard time connecting to it with C#.
Here's the code I'm using, much of the stuff I've tried out is commented out:
using System;
using System.Collections.Generic;
//using System.Data.Common.DbConnection;
using System.Threading;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Threading;
namespace mvpde
{
class Program
{
class DataReader_SQL
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
try
{
OleDbConnection con = new OleDbConnection(#"Provider=sqloledb;Data Source=127.0.0.1:3306;database=database_name;User id=id;Password=password;");
con.Open();
//Thread.Sleep(9999);
//SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
//builder.DataSource = "localhost";
//builder.UserID = "hello";
//builder.Password = "password";
//builder.InitialCatalog = "db_123";
//SqlConnection thisConnection = new SqlConnection(builder.ToString());
//thisConnection.Open();
//SqlCommand thisCommand = thisConnection.CreateCommand();
//thisCommand.CommandText = "SELECT CustomerID, CompanyName FROM Customers";
//SqlDataReader thisReader = thisCommand.ExecuteReader();
//while (thisReader.Read())
//{
// Console.WriteLine("\t{0}\t{1}", thisReader["CustomerID"], thisReader["CompanyName"]);
//}
//thisReader.Close();
//thisConnection.Close();
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
Thread.Sleep(9999999);
}
}
}
}
}
I've copied it nearly verbatim and tried to make it work from this site.
I have installed the MySQL on Windows 7 - I have created the user and the database I'm trying to access and I can do all this just fine using MySQL's own MySQL Workbench 5.2 CE software. I seem to have no clue what I'm doing using C# to connect to it.
All I want is to connect to it and send it a simple query like "USE DATABASE somedb" and then "SELECT TABLE sometable".
Errors I'm getting:
At first (when I used WAMP, before installing the MySQL package from mysql website) I would be able to connect once and see a login error; after that, it's as if the connection wasn't closed properly and I'd be unable to get even that far)
Now that I'm trying to connect to a MySQL instance that is created by MySQL's own software (or by running mysqld.exe) all I ever get is timeout problems\server not found\inaccessible.
Questions:
Am I using the wrong class?
What's the deal with "Provider="? where is the list of all the available variables for that part of the string? What does it mean? Why are the names involved so cryptic?
I imagined connecting to a locally-running MySQL server should be a breeze, but I've no idea what I'm doing.
Thank you.
You should use the MySql/Connector for DotNet.
Download it at this address then change your connection string accordingly.
For example "Server=127.0.0.1;Database=database_name;Uid=id;Pwd=password;Port=3306"
For other options, specific for MySQL, look at www.connectionstrings.com
have you had a look at http://www.connectionstrings.com/mysql ?
You can't use a SQL Connection object. You need a MySQL Connection object which is available in this library.http://www.connectionstrings.com/mysql
Download the MySQL Connection Library and use one of their connection strings provided on the site.
using MySql.Data.MySqlClient;
MySqlConnection myConnection = new MySqlConnection;();
myConnection.ConnectionString = myConnectionString;
myConnection.Open();
//execute queries, etc
myConnection.Close();
Then use the connection object to initalise the connection string and connect to MySQL

How to Connect to SQL Server Programmatically in C#?

I have developed a program (C#) which creates a SQL database using this code:
string SQLCreation = "IF NOT EXISTS (SELECT * FROM master..sysdatabases WHERE Name = 'x') CREATE DATABASE x";
SqlConnection PublicSQLDBCreationConnection = new SqlConnection(connectionString);
SqlCommand PublicSQLDBCreation = new SqlCommand(SQLCreation, PublicSQLDBCreationConnection);
try
{
PublicSQLDBCreationConnection.Open();
PublicSQLDBCreation.ExecuteNonQuery();
PublicSQLDBCreationConnection.Close();
}
//'then creates a table and so on
Now I want to have a client application which connects to this database (via LAN) WITHOUT using IP or computer name. How is that possible? Is it possible do this and have a dataset while not mentioning IP Adr. or computer name?
P.S. Don't Worry Guys, I simplified my code just for your view, I have made sure that SQL injection or other attempts won't happen.
Also I have to say that My Reason for not mentioning servername or IP is that I want to mass deploy my Application on many Networks
You could use SqlDataSourceEnumerator to get a list of all Sql Servers that are visible and browsable. This is not a good technique, since you could get an instance that you don't have the right to create a database on it, but you could still try something with that.
var enumerator = SqlDataSourceEnumerator.Instance;
foreach (DataRow row in enumerator.GetDataSources().Rows)
{
var serverName = row["ServerName"];
var instance = row["InstanceName"];
// build a connection string and try to connect to it
}

What is the best way for me to connect to a offline database through C#

I have an application that needs to store loads of data in a table format. I want something easy to configure, which is also in built with C#.NET. I don't want to have to include additional DLL files.
Also some links to tutorials, explaining the connection process and querying would be great. I'm assuming this is just like PHP, but which database type do I need?
It needs to be able to hold a lot of data and the ability to perform backups would be nice.
I'm not sure what you mean by "built in with C#.NET", but SQL Server Express comes with Visual Studio.
If you're looking for "a self-contained, embeddable, zero-configuration SQL database engine", you could try System.Data.SQLite.
If you want an offline database you could use SQL Server CE, as its a in-process database that does not require being attached to a server instance, which is really what you want then. Here is an example in C# on how you would connect, and populate a data table to manipulate some data.
// this connectionstring can also be an absolute file path
string connectionString = "Data Source=|DataDirectory|\mydatabase.sdf";
using (SqlCeConnection connection = new SqlCeConnection(connectionString)) {
try {
connection.Open();
}
catch (SqlCeException) {
// connection failed
}
using (SqlCeDataAdapter adapter = new SqlCeDataAdapter("SELECT * FROM <table>", connection)) {
using (DataTable table = new DataTable("<table>")) {
adapter.Fill(); // Populate the table with your select statement
// do stuff with the datatable
// example:
foreach (DataRow row in table.Rows) {
row["mycolumn"] = "somedata";
}
table.AcceptChanges();
}
}
}
You can even use commands instead of data tables
using (SqlCeCommand command = new SqlCeCommand("DELETE FROM <table> WHERE id = '0'", connection)) {
command.ExecuteNonQuery(); // executes command
}
Have a look at the ease of SQL Server Compact
Not build-in but easily added, no install and free.

Connection String Problem Oracle .Net

I am new to oracle and am trying to simply connect to an oracle db, but I am not sure where to find the proper credentials to put in the connection string. I simply downloaded and install oracle express edition on my machine, then installed the .Net references. My simple code is here:
string oradb = "Data Source=XE;User Id=hr;Password=hr;";
OracleConnection conn = new OracleConnection(oradb); // C#
try
{
conn.Open();
string sql = "SELECT FIRST_NAME FROM EMPLOYEES WHERE EMAIL='SKING'"; // C#
OracleCommand cmd = new OracleCommand(sql, conn);
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader(); // C#
dr.Read();
//label1.Text = dr["dname"].ToString(); // C# retrieve by column name
label1.Text = dr.GetString(0).ToString(); // return a .NET data type
//label1.Text = dr.GetOracleString(0).ToString(); // return an Oracle data type
}
catch (OracleException ex)
{
label1.Text = ex.Message;
}
finally
{
conn.Close();
}
I am getting a TNS:could not resolve the connect identifier specified exception. Its probably because my connection string is wrong is what I am guessing. I cannot even go to the Server Explorer dialog in Visual Studio and test a connection correctly to my oracle db.
What steps do I need to take to figure out the proper credentials to plug into my connection string?
Or wording it like this....
If you were going to install oracle express on your machine, then connect to a .Net app what steps would you take to set up the connection string?
Maybe it is looking for a data source defined in a tnsnames.ora file called XE.
Try the Easy Connect naming method in the Express edition. It enables application clients to connect to a database without using any configuration files, simply by specifying the data source attribute through syntax shown below:
user id=hr;password=hr;data source=hr-server
user id=hr;password=hr;data source=hr-server:1521
user id=hr;password=hr;data source=hr-server:1521/XE
Replace hr-server with the dns name or ip of your machine.

Categories