Join tables from two databases in C# - c#

With SQL Server I run this query with no problem...
SELECT SUM(Esi) AS Dispo
FROM [mdb].[dbo].[Query1] AS A
INNER JOIN [mdb2].[dbo].[TieCol] as B ON A.Alias=B.IDAlias
WHERE Alias LIKE 'SETUP%'
I join two tables that reside in two different databases (mdb and mdb2).
But how can I do it in my .NET application?
When I need to use this statement
string cmdText = "SELECT SUM(Esi) AS Dispo
FROM [mdb].[dbo].[Query1] AS A
INNER JOIN [mdb2].[dbo].[TieCol] as B ON A.Alias=B.IDAlias
WHERE Alias LIKE 'SETUP%'";
this.OP = new SqlConnection(ConfigurationManager.ConnectionStrings["mdb2"].ConnectionString);
SqlCommand sqlCommand = new SqlCommand(cmdText, this.OP);
I can't execute it, since this.OP is the connection to mdb2... And for mdb?
How can I connect to both databases simultanously?

The SQL connection is to the server - the Initial catalog in a connection string behaves like use - it sets the default DB.
So your 3 part SQL query should work as is. So possibly
Make sure that the SQL login used by your app (or the account of your AppPool if using Web and Integrated Security) has the necessary access to both databases. (use RunAs on SQL Enterprise Manager as this account and try to run the query)
You might try escaping [Alias]
Also, if there is coupling between mdb1 and mdb2 (e.g. SPROCS in mdb1 use tables in mdb2 etc), for ease of maintenance, you might consider adding views in mdb1 for mdb2 objects. This allows for easy identification of cross-database dependencies. In this case, your query can use views which look like they are in the same database, although the underlying dependency on mdb2 is still there.

I'm not sure if there is a way to do this within the connection string. But you can probably do it using a four part reference to the table: [server].[database].[table].[column].

Your C# application only need to connect to one database server for this query.
Say your C# application connect to [mdb]. Database [mdb2] should b linked server in database [mdb].
Since you can run that query in sql server, so there must be one sql server connected to both databases. use that sql server in your C# connection string. That's it!

Related

Sql equivalence of MySql Connection String (C#)

I have an application in C# that connects to a MySql application, and it works great. I need to build the same thing for a Sql database, but I'm find how to build the same connection string.
Which would be the equivalence o this line? Does it remain the same?
Allow User Variables=True;respect binary flags=false; Connection Timeout=10; Pooling=false
Allow User Variables=true: SQL Server has no need for this because it allows user variables by default.
Respect Binary Flags=false: There is no equivalent for this in SQL Server. It makes Connector/NET treat some BLOB columns as TEXT which shouldn't be required if the column types are created correctly in the new DB.
Connection Timeout=10: use ConnectTimeout=10 or Connection Timeout=10 for SqlClient.
Pooling=false: Use Pooling=false for SqlClient.

Connect to a SQL Server database on another network via asp.net and c#

I have a customer database that is kept on a SQL Server on our local network. I would like to create a customer portal that will be on our website that is hosted through another company. How would I connect to that SQL Server database?
Give the website host access rights to the sql server. Assuming Sql Server 2008; go to your management studio and right click the server (root) in the object explorer window and go to properties. You can manage permissions from there. Also, it will show you the "server" to use in your connection string (something like [server]\SQLEXPRESS, which can be used locally and remotely).
Create a proper connection string in the website, preferably in web.config, to use for all of your connections to the database. You can then get this connection string from, say, your data layer via
ConfigurationManager.ConnectionStrings["ConnString_Name"].ConnectionString;
Aside from the correct connection string, you will also need to ensure that the website can communicate with your SQL Server. If you have firewalls, you'll need to configure ports if they are blocked.
The alternative is to create a web service that is hosted on a DMZ zone that will communicate with your sql server internally. The website (hosted by the third party) would communicate via this web service to get the data (you can setup authentication so only those with rights can use this web service). By going this route, you're not exposing your internal sql server directly.
This answer is based on some assumptions because question does not provide all the required information.
For this you need to set ConnectionString property for your connection object.
For example
Data Source=yourIP;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;
Here is MSDN link connectionStrings
This is a example of SQLExpress connectionstring in Web.Config
<connectionStrings>
<add
name="LocalSqlServer"
connectionString="data source=.\SQLEXPRESS;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
There is a Beginners guide on Code Project which is voted 5, it will give you all you need to get started.
But before you start working with the code, I suggest that you first test the connection with SQL Server management studio. make sure that you can connect and query some data, otherwise you may face some more confusion while trying to pull this off with code only at the first time.
To connect to SQL Server from C#.NET, you need to create a connection string such as below:
private SqlConnection connection; private string connectionString = #"Server=(local);Database=Embedding_SQL_Test;User ID=sa;Password=123"; connection = new SqlConnection( connectionString );
Next, you use the SqlConnection object created above to create a 'SqlCommand', as shown below:
SqlCommand cmd = new SqlCommand( "select * from Customer where CustomerID = #Cid", connection);
The SQL query shown here can be replaced by a SELECT, INSERT, UPDATE queries etc.
Next to execute the SQL queries in the database, you use the following methods: ExecuteReader - to execute SELECT queries ExecuteNonQuery - to execute INSERT, DELETE, UPDATE, and SET statements.
This is a very short description of how to connect to SQL Server database from C# and execute SQL queries in the database. For details about the connection string, the methods and their parameters check the following link: ( http://www.shahriarnk.com/Shahriar-N-K-Research-Embedding-SQL-in-C-Sharp-Java.html ) Here you will also find details about how to pass parameters to the SQL queries as well as calling stored procedures and much more.

how to compare two values from different databases in one SQL statements

i have an idea to call two values from two different databases and comapre them in one statement? is it possible?
i am working with c# and MS-SQL
Yes.
For MSSQL you can add the database name in front of your table. You normally have 4 namespaces you can use
[Server name].[database name].[owner].[table_name]
So if you want to compare two values in the one statement you should only need to join across the tables by placing the database name in front of the table name.
If the databases are on different servers then you will need to create a linked server to the side which will run your SQL so that its aware of the other sql server. You can add linked servers in Management studio or via SQL using something like sp_addlinkedserver
You may do cross database joins to compare these values:
SELECT
db1.Value as value1,
db2.Value as value2
FROM
[database1].dbo.MyTable1 as db1
INNER JOIN
[database2].dbo.MyTable as db2
ON
/* insert join clasue */
There are a few possibilities here depending on your setup. If your databases are different SQL Server installations then you will want to look at sp_linkedserver first. Once you have the ability to see both databases using the same login you could just execute the following query where db1 and db2 are the databases, dbo is the owner and tab1 and tab2 are the respective tables.
SELECT a.col1
FROM db1.dbo.tab1 a, db2.dbo.tab2 b
WHERE a.col1 = b.col2
If you should happen to lack the SQL Server permissions to create a linked server, you could create connections to each server and your client could attach to the servers using Microsoft JET library, and then you could perform the heterogeneous join client-side.

Local database, I need some examples

I'm making an app that will be installed and run on multiple computers, my target is to make an empty local database file that is installed with the app and when user uses the app his database to be filled with the data from the app .
can you provide me with the following examples :
what do I need to do so my app can connect to its local database
how to execute a query with variables from the app for example how would you add to the database the following thing
String abc = "ABC";
String BBB = "Something longer than abc";
and etc
Edit ::
I am using a "local database" created from " add > new item > Local database" so how would i connect to that ? Sorry for the dumb question .. i have never used databases in .net
Depending on the needs you could also consider Sql CE. I'm sure that if you specified the database you're thinking of using, or your requirements if you're usure you would get proper and real examples of connection strings etc.
Edit: Here's code for SqlCe / Sql Compact
public void ConnectListAndSaveSQLCompactExample()
{
// Create a connection to the file datafile.sdf in the program folder
string dbfile = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\datafile.sdf";
SqlCeConnection connection = new SqlCeConnection("datasource=" + dbfile);
// Read all rows from the table test_table into a dataset (note, the adapter automatically opens the connection)
SqlCeDataAdapter adapter = new SqlCeDataAdapter("select * from test_table", connection);
DataSet data = new DataSet();
adapter.Fill(data);
// Add a row to the test_table (assume that table consists of a text column)
data.Tables[0].Rows.Add(new object[] { "New row added by code" });
// Save data back to the databasefile
adapter.Update(data);
// Close
connection.Close();
}
Remember to add a reference to System.Data.SqlServerCe
I'm not seeing anybody suggesting SQL Compact; it's similar to SQLite in that it doesn't require installation and tailors to the low-end database. It grew out of SQL Mobile and as such has a small footprint and limited feature-set, but if you're familiar with Microsoft's SQL offerings it should have some familiarity.
SQL Express is another option, but be aware that it requires a standalone installation and is a bit beefier than you might need for an applciation's local cache. That said it's also quite a bit more powerful than SQL Compact or SQLite.
Seems like you're:
-Making a C# app that will be installed and run on multiple
computers
-That needs a local database (I'm assuming an RDBMS)
-You need to generate a blank database at installation
-You then need to be able to connect to the database and populate it when
the app runs.
In general, it seems that you need to read up on using a small database engine for applications. I'd start by checking out SQLite, especially if you need multi-OS capability (eg., your C# program will run on Microsoft's .NET Framework and Novell's Mono). There are C# wrappers for accessing the SQLite database.
I believe this question is about the "Local Database" item template in Visual Studio:
What are you considering as a database? From what little you've provided in your question, I'd suggest SQLite.
You can get sample code from their site Sqlite.NET
Not sure I fully understand what you're asking but Sqlite is a good option for lightweight, locally deployed database persistence. Have a look here:
http://www.sqlite.org/
and here for an ADO.NET provider..
http://sqlite.phxsoftware.com/
For 1)
The easiest way to provide this functionality is through SQL Server Express User Instances. SQL Server Express is free, so your user does not have to pay additional license for SQL Server, and the User Instance is file-based, which suits your requirement.
For 2)
This is a big topic. You may want to go through some of the tutorials from Microsoft to get the feeling of how to connect to DB, etc.

concurrent SqlConnection and EntityConnection to a local Sql Express Server

I'm using Linq2Entity for most of my database operations. However for database creation, table creation and initial data insertion I use plain SQL files. Therefore I need both an SqlConnection and an EntityConnection. Unfortunately the Entity Framework starts complaining that the Sql Server is not listening on the other end of the pipe.
I'm not sure what the problem is here, it could be due to user instancing. Clearing the pool of the SqlConnection or disposing the connection instance does not help.
The connection string I'm using is the following:
"Data Source=.\SQLEXPRESS; Initial Catalog=dbname; Integrated Security=SSPI;"
update:
I have tried to use the EntityConnection for database maintenance purposes but I'm running into troubles. I can't use the EntityConnection to create databases and drop databases. The following syntax is unsupported for an EntityConnection but works fine for an SqlConnection to ms SQL express.
CREATE DATABASE silverfit ON ( NAME = silverfit, FILENAME = 'c:\silverfit\silverfit.mdf' );
Also for some reason the EntityConnection does not allow me to change databases which is necessary to drop a database. I'm afraid I still need the SqlConnection to create the database and tables..
Is there a way for SqlConnections and EntityConnections to coexist for local ms SQL express databases?
Thanks,
Wouter
Have you tried creating a SqlConnection which you then pass to the constructor for your EntityConnection? One of the overloads for EntityConnection takes a MetadataWorkspace and a DbConnection (from which SqlConnection derives.) The slight drawback of this is that you must create your MetadataWorkspace manually, which gathers up the .csdl, .ssdl, and .msl files that define your workspace. However, in the long run, you should be able to share a single connection for both executing DML queries, and using Entity Framework.
I don't agree that you need a plain SQL connection and Entity connection for this task, at least as you've described it. You can execute SQL using the Entity connection. Look at EntityConnection.CreateDbCommand. Naturally, there's a danger here that you are doing DB-server-specific things on a non-DB-server-specific instance like a EntityConnection. But it probably beats having a separate connection, in this case.
Did you try to use the EntityConnection.StoreConnection to retrieve the SqlConnection and execute commands with it ?
If you're trying attaching your database file to SQL Server Express at run time, which it seems as if you are, then only one connection can be open on it at once. This is a problem for other things, not just what you're trying to accomplish. Say, for instance, you connect to 'c:\silverfit\silverfit.mdf' through the server explorer in VS and try to open one of the tables in the db. After you open the table, try running your application. It will bomb.
However, if you open up SQL Management Studio Express (you can download it here), and then attach the database to the SQL Server, the problems you are experiencing should go away. At that point you should be able to open multiple connections to your database, via SQLConnection or EntityConnection.
Attaching your database at run time to the SQL Server express engine really only works well for demoing purposes, or proof of concepts.
Is ADO.NET holding a connection open to the database through connection pooling? Try adding Pooling=False to the connection string, as this may allow the database to be closed before you drop it.

Categories

Resources