How to count the number of rows and display it - c#

I am working on a desktop application that returns list of tables that have foreign keys in a datagrid by this function.
public void GetPrimaryKeyTable()
{
//An instance of the connection string is created to manage the contents of the connection string.
var sqlConnection = new SqlConnectionStringBuilder();
sqlConnection.DataSource = "192.168.10.3";
sqlConnection.UserID = "gp";
sqlConnection.Password = "gp";
sqlConnection.InitialCatalog = Convert.ToString(cmbDatabases.SelectedValue);
string connectionString = sqlConnection.ConnectionString;
SqlConnection sConnection = new SqlConnection(connectionString);
//To Open the connection.
sConnection.Open();
//Query to select the table_names that have PRIMARY_KEYS.
string selectPrimaryKeys = #"SELECT
TABLE_NAME
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE
CONSTRAINT_TYPE = 'PRIMARY KEY'
AND
TABLE_NAME <> 'dtProperties'
ORDER BY
TABLE_NAME";
//Create the command object
SqlCommand sCommand = new SqlCommand(selectPrimaryKeys, sConnection);
try
{
//Create the dataset
DataSet dsListOfPrimaryKeys = new DataSet("INFORMATION_SCHEMA.TABLE_CONSTRAINTS");
//Create the dataadapter object
SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectPrimaryKeys, sConnection);
//Provides the master mapping between the sourcr table and system.data.datatable
sDataAdapter.TableMappings.Add("Table", "INFORMATION_SCHEMA.TABLE_CONSTRAINTS");
//Fill the dataset
sDataAdapter.Fill(dsListOfPrimaryKeys);
//Bind the result combobox with primary key tables
DataViewManager dvmListOfPrimaryKeys = dsListOfPrimaryKeys.DefaultViewManager;
dgResultView.DataSource = dsListOfPrimaryKeys.Tables["INFORMATION_SCHEMA.TABLE_CONSTRAINTS"];
}
catch(Exception ex)
{
//All the exceptions are handled and written in the EventLog.
EventLog log = new EventLog("Application");
log.Source = "MFDBAnalyser";
log.WriteEntry(ex.Message);
}
finally
{
//If connection is not closed then close the connection
if(sConnection.State != ConnectionState.Closed)
{
sConnection.Dispose();
}
}
}
Now I want to count the number of tables that fall in this category and display it in a lablel that this much of tables are under this category..
Can you guys please help me

I believe you can just use the DataSet.Tables.Count method.
http://msdn.microsoft.com/en-us/library/system.data.internaldatacollectionbase.count.aspx
Or, DataSet.Tables[i].Rows.Count

Related

How to copy Access table to SQL table in C#?

As title says I've used odbcconnection to sqlconnection and for the life of me cant get it to work.. Copied a bunch of code from this site but cant get them both to work.
The program just hangs so maybe I am doing something wrong, but would appreciate maybe a bare bones template that i could just fill in the connection details and bulk copy the table to table..
using (OdbcConnection myConnection = new OdbcConnection())
{
string myConnectionString = #"Driver={Microsoft Access Driver (*.mdb)};" +
"Dbq=//####/data/Toronto/wrkgrp/wrkgrp30/Business Risk Oversight and Control/DATA INTEGRITY/CDE/CDE Testing Portal Requirements/Migration Requirements/RCM/Mutual Funds/Mutual Funds.mdb;";
myConnection.ConnectionString = myConnectionString;
myConnection.Open();
//execute queries, etc
OdbcCommand cmd = myConnection.CreateCommand();
cmd.CommandText = "SELECT * FROM RCM_MF_New_Accounts_Samples";
OdbcDataReader reader = cmd.ExecuteReader(); // close conn after complete
DataTable myDataTable = new DataTable();
myDataTable.Load(reader);
//myConnection.Close();
string destinationConnectionString = "Data Source=####;Initial Catalog=DYOF_STAGING_BROC;User ID=;Password=;Connection Timeout=999";
SqlConnection destination = new SqlConnection(destinationConnectionString);
SqlBulkCopy bulkData;
//destination.Open();
Exception ex = null;
try
{
Console.WriteLine("step1");
bulkData = new SqlBulkCopy(destinationConnectionString, SqlBulkCopyOptions.FireTriggers);
bulkData.BulkCopyTimeout = 1;
bulkData.DestinationTableName = "Load_CTR_Sample_Account_Opening2";
bulkData.WriteToServer(myDataTable);
bulkData.Close();
Console.WriteLine("moved from here to there");
reader.Close();
//destination.Close();
}
catch (Exception e)
{
ex = e;
}
I actually wrote an ORM to make this kind of task easier.
var accessDS = new AccessDataSource(connectionString1);
var dt = accessDS.From("RCM_MF_New_Accounts_Samples").ToDataTable().Execute();
var sqlDS = new SqlServerDataSource(connectionString2);
sqlDS.InsertBulk("Load_CTR_Sample_Account_Opening2", dt).Execute();
This does not work for .NET Core.
Packages:
https://www.nuget.org/packages/Tortuga.Chain.Access/
https://www.nuget.org/packages/Tortuga.Chain.SqlServer
Read the data from Access into a DataTable:
string strConnect = #"Provider=Microsoft.ACE.OLEDB.12.0;data source=D:\Temp\MyDB.accdb";
DataTable dt = new DataTable();
using (OleDbConnection con = new OleDbConnection(strConnect))
{
OleDbCommand cmd = new OleDbCommand("SELECT * FROM MyTable", con);
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
}
Then use SqlBulkCopy to update SQL:
string strConnect = #"Data Source=GRIFFPC\SQLEXPRESS;Initial Catalog=Testing;Integrated Security=True";
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlBulkCopy bulk = new SqlBulkCopy(con))
{
bulk.DestinationTableName = "Test";
bulk.WriteToServer(dt);
}
}
Of course, there is a much easier way to go straight from Access to SQL Server, using VBA, SQL , or other methods.
https://support.office.com/en-us/article/import-or-link-to-data-in-an-sql-server-database-a5a3b4eb-57b9-45a0-b732-77bc6089b84e
https://www.sqlshack.com/six-different-methods-to-copy-tables-between-databases-in-sql-server/
Here's a basic example of bulk insert.
public void BulkInsert(DataTable employees)
{
if (employees == null)
throw new ArgumentNullException(nameof(employees), $"{nameof(employees)} is null.");
using (var con = OpenConnection())
using (var sbc = new SqlBulkCopy(con))
{
sbc.DestinationTableName = "HR.Employee";
foreach (DataColumn column in employees.Columns)
sbc.ColumnMappings.Add(column!.ColumnName, column.ColumnName);
sbc.WriteToServer(employees);
}
}
Note the foreach (DataColumn column in employees.Columns) loop. This is required so that it knows the column names are the same in the source and the target table. (If they're not the same, manually map them in the same fashion.)
Source: https://grauenwolf.github.io/DotNet-ORM-Cookbook/BulkInsert.htm#ado.net
Following option need to verify
1) Column Name should be the same.
2) verify the column length.
3) verify the data type.

How to get changes to dataset and save changes to database

I have a program that reads data from database and displays it onto spreadsheetcontrol(devexpress).
I would like your help in enabling the program to get changes to the dataset on button_click, and then save it back into the database.
Thanks
here is a snippet of the code
mentwall_DataDataSet ds = new mentwall_DataDataSet();
mentwall_DataDataSetTableAdapters.DATABASETableAdapter databaseAdapter = new mentwall_DataDataSetTableAdapters.DATABASETableAdapter();
databaseAdapter.Fill(ds.DATABASE);
dv = new DataView(ds.DATABASE);
mentwall_DataDataSet ds2 = new mentwall_DataDataSet();
mentwall_DataDataSetTableAdapters.RegsTableAdapter regsAdapter = new mentwall_DataDataSetTableAdapters.RegsTableAdapter();
regsAdapter.Fill(ds2.Regs);
dv2 = new DataView(ds2.Regs);
This binds the data source
Worksheet worksheet = workbook.Worksheets[2];
worksheet.DataBindings.BindToDataSource(dv, 1, 0);
Worksheet worksheet2 = workbook.Worksheets[3];
worksheet2.DataBindings.BindToDataSource(dv2, 1, 0);
I have done exactly the same, an application which shows content of a SQL table in a DevExpress Grid Control ( Windows Forms ) and when i click save button all changes ( including new rows added or deleted rows ) are persisted to the SQL Server database, here is a snippet of my DAL class which handles the database logic of saving:
the main point here is to use the SqlCommandBuilder class, which must be initialized with at least the select command and then all other commands are generated automatically, I have written this code > 5 years ago and i still use this app daily.
public int UpdateSQLDataTable(string connectionString, string TableName, DataTable dtSource)
{
try
{
using (SqlConnection sConn = new SqlConnection(connectionString))
{
sConn.Open();
var transaction = sConn.BeginTransaction();
try
{
var command = sConn.CreateCommand();
command.Transaction = transaction;
command.CommandText = $"SELECT TOP 1 * FROM {TableName} WITH (NOLOCK)";
command.CommandType = CommandType.Text;
// timeoput of 5 minutes
command.CommandTimeout = 300;
SqlDataAdapter sAdp = new SqlDataAdapter(command);
SqlCommandBuilder sCMDB = new SqlCommandBuilder(sAdp);
int affectedRecords = sAdp.Update(dtSource);
transaction.Commit();
return affectedRecords;
}
catch (Exception /* exp */)
{
transaction.Rollback();
throw;
}
}
}
catch (Exception exc)
{
Logger logger = new Logger();
logger.Error(string.Format("connectionString: '{0}', TableName: '{1}'", connectionString, TableName), exc);
return int.MinValue;
}
}

Converting DataTable to string type

I have a function like this
public DataTable GetAllPrimaryKeyTables(string localServer, string userName, string password, string selectedDatabase)
{
// Create the datatable
DataTable dtListOfPrimaryKeyTables = new DataTable("tableNames");
SqlConnectionStringBuilder objConnectionString = new SqlConnectionStringBuilder();
objConnectionString.DataSource = localServer; ;
objConnectionString.UserID = userName;
objConnectionString.Password = password;
objConnectionString.InitialCatalog = selectedDatabase;
// Query to select primary key tables.
string selectPrimaryKeyTables = #"SELECT
TABLE_NAME
AS
TABLES
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE
CONSTRAINT_TYPE = 'PRIMARY KEY'
AND
TABLE_NAME <> 'dtProperties'
ORDER BY
TABLE_NAME";
// put your SqlConnection and SqlCommand into using blocks!
using(SqlConnection sConnection = new SqlConnection(objConnectionString.ConnectionString))
using(SqlCommand sCommand = new SqlCommand(selectPrimaryKeyTables, sConnection))
{
try
{
// Create the dataadapter object
SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectPrimaryKeyTables, sConnection);
// Fill the datatable - no need to open the connection, the SqlDataAdapter will do that all by itself
// (and also close it again after it is done)
sDataAdapter.Fill(dtListOfPrimaryKeyTables);
}
catch(Exception ex)
{
//All the exceptions are handled and written in the EventLog.
EventLog log = new EventLog("Application");
log.Source = "MFDBAnalyser";
log.WriteEntry(ex.Message);
}
}
// return the data table to the caller
return dtListOfPrimaryKeyTables;
}
Then I wanted to get the return type as string and not as DataTable so I did this..
public string GetAllPrimaryKeyTables(string ConnectionString)
{
string result = string.Empty;
// Query to select primary key tables.
string selectPrimaryKeyTables = #"SELECT
TABLE_NAME
AS
TABLES
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE
CONSTRAINT_TYPE = 'PRIMARY KEY'
AND
TABLE_NAME <> 'dtProperties'
ORDER BY
TABLE_NAME";
// put your SqlConnection and SqlCommand into using blocks!
using(SqlConnection sConnection = new SqlConnection(ConnectionString))
using(SqlCommand sCommand = new SqlCommand(selectPrimaryKeyTables, sConnection))
{
try
{
// Create the dataadapter object
SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectPrimaryKeyTables, sConnection);
DataTable dtListOfPrimaryKeyTables = new DataTable("tableNames");
// Fill the datatable - no need to open the connection, the SqlDataAdapter will do that all by itself
// (and also close it again after it is done)
sDataAdapter.Fill(dtListOfPrimaryKeyTables);
using(StringWriter sw = new StringWriter())
{
dtListOfPrimaryKeyTables.WriteXml(sw);
result = sw.ToString();
}
}
catch(Exception ex)
{
//All the exceptions are handled and written in the EventLog.
EventLog log = new EventLog("Application");
log.Source = "MFDBAnalyser";
log.WriteEntry(ex.Message);
}
}
// return the data table to the caller
return result;
}
But this is not returning the string which it should ...
Can you direct me to the point that required modifications.
Instead of a StringWriter, use a StringBuilder, then you can use the Write and WriteLine methods.
If you want a comma seperated list, you could use something like below.
private string GetList(ds)
{
var result = string.Empty;
for(int i = 0; i < ds.Rows.Count; i++)
{
result += ds.Row[i][0] + ",";
}
result = result.Trim(',');
return result;
}
Hope this helps.

Defining function in one class and calling in other class is not inheriting the controls

I have defined the function in one class like
public static DataSet GetAllPrimaryKeyTables()
{
//An instance of the connection string is created to manage the contents of the connection string.
using(var sConnection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]))
{
//To Open the connection.
sConnection.Open();
//Query to select the table_names that have PRIMARY_KEYS.
string selectPrimaryKeys = #"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME <> 'dtProperties'
ORDER BY TABLE_NAME";
//Create the command object
using(var sCommand = new SqlCommand(selectPrimaryKeys, sConnection))
{
try
{
//Create the dataset.
DataSet dsPrimaryKeyTables = new DataSet("INFORMATION_SCHEMA.TABLE_CONSTRAINTS ");
//Create the dataadapter object.
SqlDataAdapter daPrimaryKeyTables = new SqlDataAdapter(selectPrimaryKeys, sConnection);
//Provides the master mapping between the sourcr table and system.data.datatable
daPrimaryKeyTables.TableMappings.Add("Table", "INFORMATION_SCHEMA.TABLE_CONSTRAINTS ");
//Fill the dataadapter.
daPrimaryKeyTables.Fill(dsPrimaryKeyTables);
//Bind the result combobox with non primary key table names
DataViewManager dsvPrimaryKeyTables = dsPrimaryKeyTables.DefaultViewManager;
return dsPrimaryKeyTables;
}
catch(Exception ex)
{
//Handles the exception and log that to the EventLog with the original message.
EventLog log = new EventLog("Application");
log.Source = "MFDBAnalyser";
log.WriteEntry(ex.Message);
return null;
}
finally
{
//checks whether the connection is still open.
if(sConnection.State != ConnectionState.Closed)
{
sConnection.Close();
}
}
}
}
}
And now how should i code so that I can call that function in another class in a dafault dataset.
Will anybody please help me??
Making this function an Extension Method on DataSet type will sole your problem if I understand you,
You will use something like this.
Dataset myPrimaryKeyDataset = YourClassName.GetAllPrimaryKeyTables();
Hope this helps.

Binding data to a rich textbox control i windows application

Hi All,
I am currently binding my data in a datagrid like this
public DataTable GetAllPrimaryKeyTables(string localServer, string userName, string password, string selectedDatabase)
{
// Create the datatable
DataTable dtListOfPrimaryKeyTables = new DataTable("tableNames");
SqlConnectionStringBuilder objConnectionString = new SqlConnectionStringBuilder();
objConnectionString.DataSource = localServer; ;
objConnectionString.UserID = userName;
objConnectionString.Password = password;
objConnectionString.InitialCatalog = selectedDatabase;
// Query to select primary key tables.
string selectPrimaryKeyTables = #"SELECT
TABLE_NAME
AS
TABLES
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE
CONSTRAINT_TYPE = 'PRIMARY KEY'
AND
TABLE_NAME <> 'dtProperties'
ORDER BY
TABLE_NAME";
// put your SqlConnection and SqlCommand into using blocks!
using(SqlConnection sConnection = new SqlConnection(objConnectionString.ConnectionString))
using(SqlCommand sCommand = new SqlCommand(selectPrimaryKeyTables, sConnection))
{
try
{
// Create the dataadapter object
SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectPrimaryKeyTables, sConnection);
// Fill the datatable - no need to open the connection, the SqlDataAdapter will do that all by itself
// (and also close it again after it is done)
sDataAdapter.Fill(dtListOfPrimaryKeyTables);
}
catch(Exception ex)
{
//All the exceptions are handled and written in the EventLog.
EventLog log = new EventLog("Application");
log.Source = "MFDBAnalyser";
log.WriteEntry(ex.Message);
}
}
// return the data table to the caller
return dtListOfPrimaryKeyTables;
}
And then giving the datasource as this
protected void GetPrimaryKeyTables()
{
DataTable dtPrimaryKeys = new DataAccessMaster().GetAllPrimaryKeyTables(txtHost.Text, txtUsername.Text, txtPassword.Text, Convert.ToString(cmbDatabases.SelectedValue));
dgResultView.DataSource = dtPrimaryKeys;
}
But now I need to bind the datatable to a richtextbox control available in the toolbox.
Waiting for reply!!!
How to do that??
I don't think you can bind a dataTable to a RichTextBox "as is" because the structure of the two elements are intrinsically different. you can't "magically" bind a multi-element table to a single element string-containing element. IMHO you should extract the string from DB and put it into (or bind it as a string) your RichTextBox Control.

Categories