I am trying to compare two databases from different dates. I want to load my 'Orders' table from the ending database into a DataTable, then convert that DataTable to a Dictionary<string,int> where string = OrderNumber and int = ClientNumber.
Once I have the Dictionary into memory, I will run my function that goes out to the beginning database and performs a atrOrdersEND.ContainsKey(ordernumber) check. If it is exists nothing will be done, if it does not exist, I want the information of the DataRow to be saved somewhere.
Is this the best way to go about this?
If not, how should I?
static public DataTable getDatabaseInfo(string DB)
{
DB = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DB;
OleDbConnection conn = new OleDbConnection(DB);
string query = "SELECT * FROM ORDERS;";
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
conn.Open();
try
{
da.Fill(dt);
}
catch (OleDbException ex)
{
}
return dt;
}
static Dictionary<string,int> ToDictionary(DataTable DT)
{ //this doesn't work, I get the 'An item with the same key has already been added' error
var Dict = (from order in DT.AsEnumerable()
select new
{
OrderNumber = order.Field<string>("OrderNumber"),
ClientNumber = order.Field<int>("Client")
}).AsEnumerable()
.ToDictionary(k => k.OrderNumber, v => v.ClientNumber);
return Dict;
}
static public void CheckHistoryBEG(string DB)
{
DB = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DB;
OleDbConnection conn = new OleDbConnection(DB);
string query = "SELECT * " +
"FROM Orders";
OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
DataTable dt = new DataTable();
try
{
adapter.Fill(dt);
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
string ordernumber = dt.Rows[i]["OrderNumber"].ToString();
if (atrOrdersEND.ContainsKey(ordernumber))
{
atrOrdersEND[ordernumber] = atrOrdersEND[ordernumber] + 1;
}
else
{
atrOrdersEND.Add(ordernumber, 1);
}
}
}
catch (OleDbException ex)
{
}
}
public Main()
{
DataTable EndDB_Data = getDatabaseInfo(endDBLocation);
Dictionary<string, int> atrOrdersBEG = ToDictionary(EndDBData);
CheckHistoryBEG(beginningDBLocation);
}
You can avoid writing any C# code by using linked tables in your MS Access database. From one DB you can reference the table in the other database. Then you can do joins or existence queries between the two databases.
Related
public static SqlConnection OpenConnection2DB()
{
string s = #"Data Source=********;Initial Catalog=Parking;User ID=sa;Password=*******";
SqlConnection KetNoi = new SqlConnection(s);
KetNoi.Open();
return KetNoi;
}
public static void DongKetNoi(SqlConnection KetNoi)
{
KetNoi.Close();
}
public static DataTable TruyVanLayDuLieu(string sTruyVan, SqlConnection KetNoi)
{
SqlDataAdapter da = new SqlDataAdapter(sTruyVan, KetNoi);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
public static DataTable GetDataForm2DB()
{
string sTruyVan;
sTruyVan = "SELECT * FROM[parking].[dbo].[TicketMonth] AS A INNER JOIN[fishcm - cardlog].[dbo].[Cardlog] as B ON A.ID = B.ID and A.Stt = B.Stt";
con = OpenConnection2DB();
DataTable dt = TruyVanLayDuLieu(sTruyVan, con);
if (dt.Rows.Count == 0)
{
return null;
}
return dt;
}
The query is right, I checked it with SMSS and it works. My problem is how to open connection for 2 databases on the same server, parking and fishcm - cardlog.
I was looking for around, and see more people advised open 2 connection strings. But it is good in this case, both of databases cannot collate data with each other?
public queue getQueueDataByID(int queueID)
{
string DBConnect = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
SqlDataAdapter da;
DataSet ds = new DataSet();
queue myQueue = new queue();
StringBuilder sqlCommand = new StringBuilder();
sqlCommand.AppendLine("Select * from QueueTable where");
sqlCommand.AppendLine("id = #paraId");
try
{
SqlConnection myConn = new SqlConnection(DBConnect);
// sqlCommand.Parameters.AddWithValue("paraCustId", tbCustId.Text);
da = new SqlDataAdapter(sqlCommand.ToString(), myConn);
da.SelectCommand.Parameters.AddWithValue("paraId", queueID);
// fill dataset
da.Fill(ds, "QueueTable");
//conn.Close();
int rec_cnt = ds.Tables["QueueTable"].Rows.Count;
DataRow row = ds.Tables["QueueTable"].Rows[rec_cnt-1 ];
myQueue.queueNo = row["QueueNo"].ToString();
myQueue.NRIC = row["NRIC"].ToString();
myQueue.ContactNo = row["ContactNo"].ToString();
}
catch (SqlException ex)
{
}
return myQueue;
}
This is my class,I am trying to retrieve the datas from the last row of the database to display in a web form, any idea how i can do that? My "id", primary key is set as autoincrement.
You can use Linq on the datatable to get the last row.
var queueDataTable = ds.Tables[0];
var lastDataRow = queueDataTable.AsEnumerable().Last();
If you need to itterate through all the rows in the datatable
foreach (var dataRow in queueDataTable.AsEnumerable())
{
}
thanks
Here is my code:
private List<string> readFromDatabase()
{
SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=" + fileName + ".sqlite;Version=3;");
string sql = "SELECT * FROM formsData";
m_dbConnection.Open();
SQLiteDataReader dr = DatabaseHandler.ExecuteCommandReader(sql, m_dbConnection);
List<string> tempList = new List<string>();
if(dr.HasRows)
{
while (dr.Read())
{
tempList.Add(Convert.ToString(dr["fieldName"]));
tempList.Add(Convert.ToString(dr["dataType"]));
tempList.Add(Convert.ToString(dr["numberOfCharacters"]));
}
}
return tempList;
}
I am trying to make it add each value from the database into the list, however it is only adding the last value found, from the final column. Does anyone know how to solve this? Thank you...
you can use a DataTable instead of DataReader (even though its possible to achieve the same result with DataReader).
please check that discussion: Why is DataTable faster than DataReader.
also its a better practice to use Try-Catchsteatments when connecting to databases.
here is an example (based on your code) how to achieve that task usingDataTable:
private List<string> readFromDatabase()
{
DataTable dt = PullData();
List<string> tempList = new List<string>();
if (dt != null & dt.Rows.Count >0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
tempList.Add(Convert.ToString(dt.Rows[i]["fieldName"]));
tempList.Add(Convert.ToString(dt.Rows[i]["dataType"]));
tempList.Add(Convert.ToString(dt.Rows[i]["numberOfCharacters"]));
}
}
return tempList;
}
public DataTable PullData()
{
try
{
string connString = #"your connection string here";
string query = "select * from table";
DataTable dataTable = new DataTable();
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(dataTable);
conn.Close();
da.Dispose();
return dataTable;
}
catch (Exception ex)
{
return null;
}
}
Make sure your record set is positioned at the first row before you start iterating through it.
Also, do you really want to take all the rows of the table and have them as sequential values in a list? Perhaps adding them to class might make more sense.
public class Record{
public string Name { get; set; }
public string Type { get; set; }
public int Size { get; set; }
}
I am trying to a get the Row values from a excel sheet, based on the column Value.
e.g. I have CutsomerID as lets say 5 , so I want First name 5, last Name 5 and Address 5
I am converting whole excel sheet into DataTable and then trying to read on each DataRow, when I get CustomerID as 5, I copy all the values and break from the loop
Here is my code and it is working fine as well, but I was wondering is there any way to optimise it.
Here is my Code.
public ExcelData GetDataByCustomerID(String excelFilePath, String customerID)
{
OleDbConnectionStringBuilder connectionStringBuilder = new OleDbConnectionStringBuilder();
connectionStringBuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
connectionStringBuilder.DataSource = excelFilePath;
connectionStringBuilder.Add("Mode", "Read");
const string extendedProperties = "Excel 12.0;IMEX=1;HDR=YES";
connectionStringBuilder.Add("Extended Properties", extendedProperties);
String connectionString = connectionStringBuilder.ToString();
// Create connection object by using the preceding connection string.
using( var objConn = new OleDbConnection(connectionString))
{
objConn.Open();
// Get the data table contaning the schema guid.
DataTable excelSheetsDataTable = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (excelSheetsDataTable == null)
return null;
// get all the tables in the Sheet
List<String> excelSheets = (from DataRow row in excelSheetsDataTable.Rows select row["TABLE_NAME"].ToString()).ToList();
// Our data is on First sheet only
OleDbCommand _oleCmdSelect = new OleDbCommand(#"SELECT * FROM [" + excelSheets[0] + "]", objConn);
OleDbDataAdapter oleAdapter = new OleDbDataAdapter();
oleAdapter.SelectCommand = _oleCmdSelect;
DataTable newDataTable = new DataTable();
oleAdapter.FillSchema(newDataTable, SchemaType.Source);
oleAdapter.Fill(newDataTable);
if (newDataTable.Columns.Contains("CustomerID"))
{
foreach (DataRow rowValue in newTB.Rows)
{
if ((string) rowValue["CustomerID"] == customerID)
{
var data = new ExcelData
{
customerFirstName = rowValue["Customer_First_ Name"].ToString(),
customerLastName = rowValue["Customer_Last_Name"].ToString(),
customerAddress = rowValue["Customer_Address"].ToString(),
};
return data;
}
}
String message = String.Format("The CustomerID {0} not found in Excel file {1}", customerID, excelFilePath);
MessageBox.Show(message);
}
else
{
String message = String.Format("The Column CustomerID not found in Excel file {0}", excelFilePath);
MessageBox.Show(message);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return null;
}
public class ExcelData
{
public String customerID;
public String customerFirstName;
public String customerLastName;
public String customerAddress;
}
Change your select query to like below -
#"SELECT * FROM [" + excelSheets[0] + "] WHERE CustomerID=<your_value>"
Courtesy msdn web site:
Link: MSDN
DataTable dt;
private void button1_Click(object sender, EventArgs e)
{
try
{
openFileDialog1.ShowDialog();
string connectionString = string.Format("Provider = Microsoft.Jet.OLEDB.4.0;Data Source ={0};Extended Properties = Excel 8.0;", this.openFileDialog1.FileName);
var con = new OleDbConnection(connectionString);
var cmd = new OleDbCommand("select * from [sheet1$] where [MRN#]=#c", con);
cmd.Parameters.Add("#c", "33264");
con.Open();
var dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dt = new DataTable();
dt.Load(dr);
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
DataGridView dv = new DataGridView();
this.Controls.Add(dv);
dv.DataSource = dt;
}
}
EDIT:
As per your code you should try the below lines of code:
OleDbCommand _oleCmdSelect = new OleDbCommand(#"SELECT * FROM [" + excelSheets[0] + "]" + " Where [CustomerID#] = #custID" , objConn);
_oleCmdSelect.Parameters.Add("#custID", customerID);
OleDbDataAdapter oleAdapter = new OleDbDataAdapter();
oleAdapter.SelectCommand = _oleCmdSelect;
I have a homework about database connection via ms access.
I prepared my database and saved it as dbMert and put it to debug / bin
This is my CustomerDatabase class for connecting to database:
static class CustomerDatabase
{
static string connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=dbMert.mdb";
static OleDbConnection connection = null;
static OleDbCommand command = null;
public static void ConnectToDatabase()
{
if (connection == null)
{
connection = new OleDbConnection(connectionstring);
command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * from Customer";
}
}
public static DataTable executeSelect(string sql)
{
ConnectToDatabase();
DataTable dt = null;
dt = new DataTable();
command.CommandText = sql;
OpenConnection();
OleDbDataReader datareader = command.ExecuteReader();
dt.Load(datareader);
datareader.Close();
CloseConnection();
return dt;
}
public static void OpenConnection()
{
try
{
if (connection != null)
{
connection.Open();
}
}
catch (Exception ex)
{
}
}
public static void CloseConnection()
{
if (connection != null)
{
connection.Close();
}
}
}
}
Form: In constructor i try to connect to database
public Form1()
{
InitializeComponent();
CustomerDatabase.ConnectToDatabase();
}
and in form's load i try to take tuples to datagridview but nothing happens :S
private void Form1_Load(object sender, EventArgs e)
{
string sql1 = "select * from Customer";
DataTable dt = CustomerDatabase.executeSelect(sql1);
}
Regardless of other things (such as not keeping a single connection open, using using statements etc) you're not connecting your newly-loaded DataTable to your DataGridView at all. Your Form1_Load method just loads the data into a DataTable, then effectively throws it away.
I suspect you want something like:
dataGridView.DataSource = dt;
at the end of the method.
EDIT: Note that this is also a really bad idea in your OpenConnection code:
catch (Exception ex)
{
}
That basically says, "If something goes wrong, don't bother recording that fact or changing how the rest of the code works - just keep going as if nothing had happened."
Why are you catching the exception at all?
Try to write simple code. I suggest you to use OleDbDataAdaper, its Fill() method populate the DataTable easily.
You may use |DataDirectory| if you are using database (.mdb) located under Bin\Debug folder.
static string connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=|DataDirectory|\dbMert.mdb";
Or
static string connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=x:\full_path\dbMert.mdb";
Or
static string connectionstring = #"Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=x:\full_path\dbMert.mdb";
static class Test
{
static string connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=dbMert.mdb";
public static DataTable executeSelect(string sql)
{
DataTable dt = new DataTable();
OleDbDataAdapter adapter = new OleDbDataAdapter(sql,connectionString);
adapter.Fill(dt);
return dt;
}
}
Add following code in form_load handler,
string sql1 = "select * from Customer";
DataTable dt = Test.executeSelect(sql1);
DataGridView1.DataSource=dt;
When I move the DB-file to bin/debug, an error message states "4.0 is not installed".
However, when I move it to bin, the problem is solved.
My code:
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source= ..\\dbMert.mdb";
con.Open();
recordları
DataSet ds = new DataSet();
DataTable dt = new DataTable();
ds.Tables.Add(dt);
OleDbDataAdapter da = new OleDbDataAdapter();
da = new OleDbDataAdapter("Select * from Customer", con);
da.Fill(dt);
dataGridView1.DataSource = dt;
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn col in dt.Columns)
if(col.ToString() == "emailAdress")
comboBox1.Items.Add(row[col]);
}
con.Close();