How to implement "Right Outer Join" query in access database using C#? - c#

I want to write RightOuterJoin query to retrieve data from access database.. How can i implement this query in c#?
I tried Like this
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=Sample1.accdb; Jet OLEDB:Engine Type=5";
string sql = "SELECT t1.mobileno,t1.RetailerNo,t1.custcode,t2.RET NO FROM [C:\\Sample1.accdb].[Table1] as t1 RIGHT OUTER JOIN [C:\\Sample1.accdb].[Table2] as t2 ON t1.RetailerNo = t2.RET NO";
database = new OleDbConnection(connectionString);
database.Open();
OleDbCommand cmd1 = new OleDbCommand(sql, database);
OleDbDataAdapter da = new OleDbDataAdapter(cmd1);
//database.Open();
//conn.Open();
cmd1.ExecuteNonQuery();
System.Data.DataTable dt = new System.Data.DataTable();
da.Fill(dt);

I think you may have a problem with your connection string. It uses the Jet provider, but the database type is the newer ACCDB format. Jet does not work with ACCDB.
For ACCDB, you need the ACE provider. If you don't have Office 2007 or 2010 installed, you can download and install the Access Database Engine Redistributable.
Here is the provider section from a working connection string:
Provider=Microsoft.ACE.OLEDB.12.0
See Connection strings for Access 2007 for more details.
Once you have a working connection to Sample1.accdb, revise your SQL statement to this:
SELECT t1.mobileno,t1.RetailerNo,t1.custcode,t2.[RET NO]
FROM
Table1 as t1
RIGHT JOIN Table2 as t2
ON t1.RetailerNo = t2.[RET NO]
Notes:
Since you're already connected to Sample1.accdb, you don't need to prefix the table names with the path to the db file.
For a field name which includes a space (RET NO), enclose the field name in square brackets.

Try the following code
select * from tblemp right join tblDept on tblemp.DeptId=tblDept.pkDeptId
Its is the same as you use right join in SQL SERVER.

Related

Ado.Net DBase driver truncates cells with tab character

I am trying to access to an old DBase file with Ado.Net C#. I successfully opened file but some string records in table has TAB character like "Some text/TABOther text". Ado.Net driver successfully reads "Some text" and can not read rest of the data. Is there are a way to let Ado.Net read all the content of the cell?
My connection string:
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=DATA DIRECTORY;Extended Properties=dBASE IV;User ID=;Password=;";
Select query:
var sql = "select * from " + "MY_TABLE";
OleDbCommand cmd = new OleDbCommand(sql, con);
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds);
I would use VFPOLEDB driver from Microsoft.Jet driver is good for maybe dBase II but not trustable for the later versions (like dBase IV).
DataTable tbl = new DataTable();
new OleDbAdapter("select * from MY_TABLE",
"Provider=VFPOLEDB;Data Source=DATA DIRECTORY",
).Fill(tbl);
And be sure you only have TAB character in between. While xbase databases can store any character in a string field, in C# (contrary to documentation) strings are ASCIIZ strings like in C. Also if that string has NEWLINE character in it, in DataTable you might not see that.
PS: Try posting to Visual-Foxpro tag next time. That one has more interest.

Read excel via ADO.NET with SQL Server commands?

I can read XLS file with this code :
string path =#"c:\r\1.xlsx";
OleDbConnection MyConnection = new OleDbConnection(#"provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + path + #"';HDR=Yes;Jet OLEDB:Engine Type=37");
OleDbDataAdapter MyCommand = new OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
DataSet DtSet = new DataSet();
MyCommand.Fill(DtSet);
...
...
However - when I enhance the query to include some SQL Server commands like
select *,case when 1=1 then 'a' else 'b' end as rr from [Sheet1$]
it goes BANG
I know that OLEDB is using access jet/ace behind the scenes.
How can use pure T-SQL query here?
You have to use IIF in querying excel
select *,
IIF(1 = 1, 'a', 'b') as rr
from [Sheet1$]
And, to create a multiple case statement, just nest them, like this:
select *,
IIF(1 = 1, 'a', IIF( 2 = 2, 'c', 'b')) as rr
from [Sheet1$]
As to whether you can use a pure MSSQL query, I do not believe that any connection that you can use with excel supports the CASE statement. So, you will have to use the above solution

Basic start with Visual Studio C# and SQL Compact (connect, select, insert)?

I'm trying to learn about C# with SQL CE so that my program can remember stuff.
I have created a database and can connect to it:
SqlCeConnection conn =
new SqlCeConnection(#"Data Source=|DataDirectory|\dbJournal.sdf");
conn.Open();
And it connects right, I guess cause if I rename the dbJournal.sdf to something wrong it doesn't debug right.
Let's say I want to make a simple SELECT query.
(SELECT * FROM tblJournal)
How is that done?
What about a simple insert?
(INSERT TO tblJournal (column1, column2, column2) VALUES
(value1, value2, value3))
I'm used to PHP and MySQL (as you properly can see :o))
#Chuck mentions EntityFramework which simplifies things and does all the work of writing the sql for you.
But there is a basic ADO.NET approach here which I will describe below.
The classes follow a standard pattern so to insert/read from sql server or other databases there are exact replica classes like SqlConnection or OleDbConnection and OleDbCommand etc
This is the most barebones ado.net approach:
using( SqlCeConnection conn =
new SqlCeConnection(#"Data Source=|DataDirectory|\dbJournal.sdf") )
using( SqlCeCommand cmd = conn.CreateCommand() )
{
conn.Open();
//commands represent a query or a stored procedure
cmd.CommandText = "SELECT * FROM tblJournal";
using( SqlCeDataReader rd = cmd.ExecuteReader() )
{
//...read
}
conn.Close();
}
Then to read data :
while (rd.Read())
{//loop through the records one by one
//0 gets the first columns data for this record
//as an INT
rd.GetInt32(0);
//gets the second column as a string
rd.GetString(1);
}
A nice and quicker way to read data is like this:
using( SqlCeDataAdapter adap =
new SqlCeDataAdapter("SELECT * FROM tblJournal", "your connection") )
{
//the adapter will open and close the connection for you.
DataTable dat = new DataTable();
adap.Fill(dat);
}
This gets the entire data in one shot into a DataTable class.
To insert data :
SqlCeCommand cmdInsert = conn.CreateCommand();
cmdInsert.CommandText = "INSERT TO tblJournal (column1, column2, column2)
VALUES (value1, value2, value3)";
cmdInsert.ExecuteNonQuery();
If you just start learning that i will suggest you to use LINQ to make that queries.
Here is MSDN article showing features of LINQ.
http://msdn.microsoft.com/en-us/library/bb425822.aspx
Using LINQ it will be simple to do every query. For example, you can write your select query like this
from journal in TblJournal select journal
or just
context.TblJournal
also in order to improve performence , you better keep the conncection open all the time when working with SQL CE (as opposed to other standard sql databases)

How to create a join across two foxpro databases using the MS Ole DB provider?

Question:
I am working with existing commercial MS Visual Foxpro application, and need to extract data from the database directly using a c# application. Unfortunately, not all of the tables are stored in the same database, some of the records are stored in a database broken down by year. How do I create a query against these two databases using a single join?
I am using Microsoft's OLE DB Provider for Visual FoxPro 9.0 (SP2)
More Detail:
Essentially, the customer information is stored in one database, and the customer purchase history is stored a database broken down by year. So I am trying to create a simple query to print out customers and their most recent purchase from this year.
In graphical form, the file structure of the db looks like this:
Data\
+-2009\
| +-MyDB.dbc
| +-Sales.dbf
+-2010\
| +-MyDB.dbc
| +-Sales.dbf
+-MyDB.dbc
+-Customers.dbf
Currently I can connect to each DB individually, and query them:
// This works to connect to the customer DB
string connectionPath1 = #"Provider=vfpoledb.1;Data Source=E:\Data\MyDB.dbc";
OleDbConnection conn1 = new OleDbConnection(connectionPath1);
OleDbCommand command1 = new OleDbCommand(#"SELECT * FROM Customers", conn1);
OleDbDataReader reader1 = command1.ExecuteReader();
// This works to connect to the annual sales record DB
string connectionPath2 = #"Provider=vfpoledb.1;Data Source=E:\Data\2010\MyDB.dbc";
OleDbConnection conn2 = new OleDbConnection(connectionPath2);
OleDbCommand command2 = new OleDbCommand(#"SELECT * FROM Sales", conn2);
OleDbDataReader reader2 = command2.ExecuteReader();
What I can't do is execute my join statement:
//How do I do this?
OleDbConnection connMagic = new OleDbConnection(connectionPath1, connectionPath2); //non-valid code
OleDbCommand commandIWant = new OleDbCommand(#"SELECT Customers.Name, Sales.Item, Sales.Date FROM Customers LEFT JOIN Sales ON (Customers.ID=Sales.CustomerID)", connMagic);
OleDbDataReader reader3 = commandIWant.ExecuteReader();
If the directory structure is as you indicate... where the different years are all UNDER the parent common, you can query to all of them directly just by including the relative path...
select
a1.Whatever,
b1.Sales1
from
Customers a1,
2009\Sales b1
where
a1.CustomerID = b1.CustomerID
union all
select
a1.Whatever,
b1.Sales1
from
Customers a1,
2010\Sales b1
where
a1.CustomerID = b1.CustomerID
union ...
you dont even have to qualify the actual DBC either, the OleDB should auto-detect it, but having it included wouldn't hurt as your original samples indicate...
Add both FoxPro tables to a DataSet either with seperate OleDbConnection objects or by reusing one OleDbConnection object. Then add a DataRelation between the 2 DataTables.
You could also try adding the DBC name to your SQL SELECT:
"SELECT c.Name, s.Item, s.Date FROM MyDB!Customers c LEFT JOIN 2009\MyDB!Sales s ON (c.ID=s.CustomerID)"

Passing data from one database to another database table

I want to take a backup of my Access database Pragmatically.
And After taking all data in backup i want to delete data from source database.
( So that it will not take much time while querying and filtering through application.)
The source database name is Data.mdb
The destination database name is Backup.mdb
Both are protected by same password.
For these purpose i am writing a query in C# like this.
string conString = "Provider=Microsoft.Jet.OLEDB.4.0 ;Data Source=Backup.mdb;Jet
OLEDB:Database Password=12345";
OleDbConnection dbconn = new OleDbConnection();
OleDbDataAdapter dAdapter = new OleDbDataAdapter();
OleDbCommand dbcommand = new OleDbCommand();
try
{
if (dbconn.State == ConnectionState.Closed)
dbconn.Open();
string selQuery = "INSERT INTO [Bill_Master] SELECT * FROM [MS Access;DATABASE="+
"\\Data.mdb" + "; Jet OLEDB:Database Password=12345;].[Bill_Master]";
dbcommand.CommandText = selQuery;
dbcommand.CommandType = CommandType.Text;
dbcommand.Connection = dbconn;
int result = dbcommand.ExecuteNonQuery();
}
catch(Exception ex) {}
Everything goes fine if i try with without password database file.
I think error in passing password on query statement.
I am trying to execute through access query but it is saying "Invalid argument".
Please is there any other programing logic for doing that.
Thanks
prashant
YuvaDeveloper
Are Data.mdb and Backup.mdb identically in strcuture? If so, I wouldn't bother copying data via SQL but just copy the whole file.
Try remove the space between the ; and Jet …
So the format would be:
INSERT INTO [Bill_Master] SELECT * FROM [MS Access;DATABASE="+
"\\Data.mdb" + ";Jet OLEDB:Database Password=12345;].[Bill_Master]
You can copy and rename Data.mdb, and then truncate all the tables in Data.mdb. Far easier than trying to copy a table at a time..
Don't delete data. This becomes a lot mroe difficult in the future to do analysis or inquiries. If it's taking a long time then review indexing or upszing to SQL Server. The Express edition is free and can handle databases up to 4 Gb.

Categories