I want to connect to multiple databases and want to run some query on through those connections, but it's not working.
string source = "10.0.0.0";
string user = "abc";
string password="abc";
DataTable dt = new DataTable();
for (int i = 0; i < dt.Rows.Count; i++)
{
string source = dt.Rows[i][2].ToString();
string user = dt.Rows[i][1].ToString();
int password = Convert.ToInt32(user) + 111;
OracleConnection conn = new OracleConnection("Data Source = " + source + ": 1521/rms; User id = " + user + "; Password=" + password + ";");
conn.Open();
OracleCommand cmd = new OracleCommand(" SELECT SUM(AI_TRN) FROM tr_rtl where DC_DY_BSN = '06-04-2016'and mall like '%" + Mallname.Text + "%' ", conn);
cmd.ExecuteNonQuery();
OracleDataAdapter oda = new OracleDataAdapter(cmd);
oda.Fill(dt);
dataGridView1.DataSource = dt;
conn.Close();
label1.Text = source;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
sorry i have posted the wrong code
What you probably will need to do is iterate through a list of connections and populate one data table with all the results. Here is an example:
List<OracleConnections> Connections = new List<OracleConnections>();
DataTable FinalResults = new DataTable();
foreach (var Connection in Connections)
{
using (Connection)
{
DataTable TemporaryTable = new DataTable();
Connection.Open();
OracleCommand Command = new OracleCommand("SomeCommandText", Connection);
OracleDataAdapter Adapter = new OracleDataAdapter(Command);
Adapter.Fill(TemporaryTable);
FinalResults.Merge(TemporaryTable);
}
}
This should give you all the results of each database/connection in one final table (Results) or you can do a dataset if it is different columns/data within each connection.
Updated to explain comments listed above.
string Source = "10.0.0.0";
string User = "abc";
string Password = "abc";
DataTable dt = new DataTable();
// Remove this or use another reference (different table), you just created the table ^, it has no rows. -> "for (int i = 0; i < dt.Rows.Count; i++)"
Related
I am new of the C# asp.net.
I have two tables. The first can be a setup table then second one is a table that wants to do a filter. I want use the setup table as the condition to search the second table then filter the result and display as gridview.
As example, the setup table got "S","50","BU2". then they will be condition to search the second table by using Select query
protected void Run_Click(object sender, EventArgs e)
{
try
{
string site = string.Empty;
string operation = string.Empty;
string bu = string.Empty;
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
using (SqlConnection conn = new SqlConnection(Contest))
{
string query = string.Empty;
conn.Open();
query = "Select Site, Operation, BU from [dbo].[Sampling_test]";
SqlDataAdapter adp = new SqlDataAdapter(query, conn);
adp.Fill(dt);
}
for (int b = 0; b < dt.Rows.Count; b++)
{
site = dt.Rows[b]["Site"].ToString();
operation = dt.Rows[b]["Operation"].ToString();
bu = dt.Rows[b]["BU"].ToString();
string[] operationArray = operation.Split(',');
string operationQuery = string.Empty;
for (int a = 0; a < operationArray.Length; a++)
{
operationQuery = operationQuery + "" + operationArray[a] + ",";
}
operationQuery.TrimEnd(',');
using (SqlConnection conn = new SqlConnection(Contest))
{
string query = string.Empty;
conn.Open();
query = "Select * from [dbo].[JHtest] where Site = '" +site+ "' AND Operation in ('" +operationQuery+ "') AND BU = '" +bu+ "' ";
SqlDataAdapter adp = new SqlDataAdapter(query, conn);
adp.Fill(dt1);
}
//insert dt into database
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["test"].ConnectionString))
{
conn.Open();
GridView2.DataSource = dt1;
GridView2.DataBind();
}
}
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
}
Can someone explain to me why it wont allow me to insert my record into MS Access?
for some reason i have tried everything that is humanly possible but it wont let me do what i need to do. what i need to do is allow record to be written from my c Sharp program and would want to press a button which will insert the value into my MS Access.
void Insert_Record(object s, EventArgs e)
{
string dbconnection = "Provider=Microsoft.ACE.OLEDB.12.0;" + #"data source =BookCSharp.accdb";
string dbcommand = "INSERT INTO BookKey, Title, Pages from Books;";
OleDbConnection conn = new OleDbConnection(dbconnection);
OleDbCommand comm = new OleDbCommand(dbcommand, conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(comm);
conn.Open();
adapter.Fill(ds, "Books");
conn.Close();
DataTable dt = ds.Tables[0];
//define a new record and place it into a new DataRow
DataRow newRow = dt. NewRow();
newRow["BookKey"] = txtBookKey.Text;
newRow["Title"] = txtTitle.Text;
newRow["Pages"] = txtPages.Text;
//add the new DataRow to DataTable
dt.Rows.Add(newRow);
//update DB
adapter.Update(ds, "Books");
//accept changes
ds.AcceptChanges();
//update listBox1
lstDisplayBooks.Items.Clear();
foreach (DataRow row in ds.Tables[0].Rows)
{
lstDisplayBooks.Items.Add(row["BookKey"] + " " + row["Title"] + " (" + row["Pages"] + ")");
}
txtBookKey.Enabled = false;
txtBookKey.Text = " ";
txtTitle.Enabled = false;
txtTitle.Text = " ";
txtPages.Enabled = false;
txtPages.Text = " ";
btnInsert.Enabled = false;
}
An OleDbDataAdapter need a SELECT query and an OleDBCommandBuilder to generate automatically the INSERT/UPDATE/DELETE commands that will be used in the Update method
void Insert_Record(object s, EventArgs e)
{
string dbconnection = "Provider=Microsoft.ACE.OLEDB.12.0;" + #"data source =BookCSharp.accdb";
string dbcommand = "SELECT * FROM Books;";
using(OleDbConnection conn = new OleDbConnection(dbconnection))
using(OleDbCommand comm = new OleDbCommand(dbcommand, conn))
{
OleDbDataAdapter adapter = new OleDbDataAdapter(comm);
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
// See comments below for these properties
builder.QuotePrefix = "[";
builder.QuoteSuffix = "]";
conn.Open();
adapter.Fill(ds, "Books");
DataTable dt = ds.Tables[0];
DataRow newRow = dt. NewRow();
newRow["BookKey"] = txtBookKey.Text;
newRow["Title"] = txtTitle.Text;
newRow["Pages"] = txtPages.Text;
dt.Rows.Add(newRow);
builder.GetInsertCommand();
adapter.Update(ds, "Books");
}
//update listBox1
lstDisplayBooks.Items.Clear();
foreach (DataRow row in ds.Tables[0].Rows)
{
lstDisplayBooks.Items.Add(row["BookKey"] + " " + row["Title"] + " (" + row["Pages"] + ")");
}
txtBookKey.Enabled = false;
txtBookKey.Text = " ";
txtTitle.Enabled = false;
txtTitle.Text = " ";
txtPages.Enabled = false;
txtPages.Text = " ";
btnInsert.Enabled = false;
}
The example in the link for the OleDbCommandBuilder contains an example like this.
The code should fix your initial error, but really there is no need to use an OleDbDataAdapter in this scenario. If your only objective is just to add a new record to the datatable and you don't need to maintain a local datasource like a DataGridView it is a lot simpler to use directly the OleDbCommand with an appropriate written INSERT and parameterized query
void Insert_Record(object s, EventArgs e)
{
string dbconnection = "Provider=Microsoft.ACE.OLEDB.12.0;" + #"data source =BookCSharp.accdb";
string dbcommand = "INSERT INTO Books (BookKey, Title, Pages) VALUES(?,?,?);";
using(OleDbConnection conn = new OleDbConnection(dbconnection))
using(OleDbCommand comm = new OleDbCommand(dbcommand, conn))
{
conn.Open();
comm.Parameters.AddWithValue("#p1", txtBookKey.Text);
comm.Parameters.AddWithValue("#p2", txtTitle.Text);
comm.Parameters.AddWithValue("#p3", txtPages.Text);
comm.ExecuteNonQuery();
}
.....
My question is how can i export gridview into MS Access in C#
for this I am Using the following code:
String accessConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\...\\test.accdb;";
String sqlConnectionString = ConfigurationManager.ConnectionStrings["College"].ConnectionString;
//Make adapters for each table we want to export
SqlDataAdapter adapter1 = new SqlDataAdapter();
// SqlDataAdapter adapter2 = new SqlDataAdapter();
DataTable dtFillGrid = (DataTable)ViewState["FillGrid"];
//Fills the data set with data from the SQL database
// DataSet dataSet = new DataSet();
adapter1.Fill(dtFillGrid);
// adapter2.Fill(dataSet, "Table2");
//Create an empty Access file that we will fill with data from the data set
ADOX.Catalog catalog = new ADOX.Catalog();
catalog.Create(accessConnectionString);
//Create an Access connection and a command that we'll use
OleDbConnection accessConnection = new OleDbConnection(accessConnectionString);
OleDbCommand command = new OleDbCommand();
command.Connection = accessConnection;
command.CommandType = CommandType.Text;
accessConnection.Open();
//This loop creates the structure of the database
foreach (DataTable table in dtFillGrid.Rows)
{
String columnsCommandText = "(";
foreach (DataColumn column in table.Columns)
{
String columnName = column.ColumnName;
String dataTypeName = column.DataType.Name;
String sqlDataTypeName = getSqlDataTypeName(dataTypeName);
columnsCommandText += "[" + columnName + "] " + sqlDataTypeName + ",";
}
columnsCommandText = columnsCommandText.Remove(columnsCommandText.Length - 1);
columnsCommandText += ")";
command.CommandText = "CREATE TABLE " + table.TableName + columnsCommandText;
command.ExecuteNonQuery();
}
//This loop fills the database with all information
foreach (DataTable table in dtFillGrid.Rows)
{
foreach (DataRow row in table.Rows)
{
String commandText = "INSERT INTO " + table.TableName + " VALUES (";
foreach (var item in row.ItemArray)
{
commandText += "'" + item.ToString() + "',";
}
commandText = commandText.Remove(commandText.Length - 1);
commandText += ")";
command.CommandText = commandText;
command.ExecuteNonQuery();
}
}
accessConnection.Close();
but in this code I get an error:
The Type or Namespace name ADOX could not be found
According to accessConnectionString content you should install "Data Connectivity Components" in your machine.
It is available to download at http://www.microsoft.com/en-us/download/details.aspx?id=23734
You need to add a reference for Microsoft ADO Ext. 2.7 for DDL and Security(the version number may be different though) which can be found under the COM section of the references dialog , and then add using ADOX; in your code.
Here I did not export gridview in MS Access but I made a database in MS Access using C# with the help of this code
ADOX.Catalog cat = new ADOX.Catalog();
ADOX.Table table = new ADOX.Table();
//Create the table and it's fields.
table.Name = "Table1";
table.Columns.Append("PartNumber", ADOX.DataTypeEnum.adVarWChar, 6); // text[6]
table.Columns.Append("AnInteger", ADOX.DataTypeEnum.adInteger, 10); // Integer
try
{
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=d:/m2.accdb;" + "Jet OLEDB:Engine Type=5");
cat.Tables.Append(table);
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0;" + "Data Source=d:/m2.accdb");
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Table1([PartNumber],[AnInteger]) VALUES (#FirstName,#LastName)";
cmd.Parameters.Add("#FirstName", OleDbType.VarChar).Value = "neha";
cmd.Parameters.Add("#LastName", OleDbType.VarChar).Value = 20;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
result = false;
}
cat = null;
I want to export grid to MS Access in C#
Here's the code that I've tried:
String accessConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\\...\\test.accdb;";
String sqlConnectionString = ConfigurationManager.ConnectionStrings["College"].ConnectionString;
SqlDataAdapter adapter1 = new SqlDataAdapter();
adapter1.Fill(dtFillGrid);
ADOX.Catalog catalog = new ADOX.Catalog();
catalog.Create(accessConnectionString);
OleDbConnection accessConnection = new OleDbConnection(accessConnectionString);
OleDbCommand command = new OleDbCommand();
command.Connection = accessConnection;
command.CommandType = CommandType.Text;
accessConnection.Open();
foreach (DataTable table in dtFillGrid.Rows) {
String columnsCommandText = "(";
foreach (DataColumn column in table.Columns) {
String columnName = column.ColumnName;
String dataTypeName = column.DataType.Name;
String sqlDataTypeName = getSqlDataTypeName(dataTypeName);
columnsCommandText += "[" + columnName + "] " + sqlDataTypeName + ",";
}
columnsCommandText = columnsCommandText.Remove(columnsCommandText.Length - 1);
columnsCommandText += ")";
command.CommandText = "CREATE TABLE " + table.TableName + columnsCommandText;
command.ExecuteNonQuery();
}
//This loop fills the database with all information
foreach (DataTable table in dtFillGrid.Rows) {
foreach (DataRow row in table.Rows) {
String commandText = "INSERT INTO " + table.TableName + " VALUES (";
foreach (var item in row.ItemArray) {
commandText += "'" + item.ToString() + "',";
}
commandText = commandText.Remove(commandText.Length - 1);
commandText += ")";
command.CommandText = commandText; command.ExecuteNonQuery();
}
}
accessConnection.Close();
How can I do this?
I would suggest you create the MDB database, create the table(s) you want using sql, then at runtime bind the gridview, or loop through the results and do a batch import.
See here: http://msdn.microsoft.com/en-us/library/windows/desktop/ms677200(v=vs.85).aspx
using ADOX; // add a COM reference to "Microsoft ADO Ext. x.x for DDL and Security"
static void CreateMdb(string fileNameWithPath)
{
ADOX.Catalog cat = new ADOX.Catalog();
string connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:Engine Type=5";
cat.Create(String.Format(connstr, fileNameWithPath));
cat = null;
}
if you dont have problem with payement you can use 'Spire doc' to save datagrid into msAccess like so :
private void btnExportToAccess_Click(object sender, EventArgs e)
{
Spire.DataExport.Access.AccessExport accessExport = new
Spire.DataExport.Access.AccessExport();
accessExport.DataSource = Spire.DataExport.Common.ExportSource.DataTable;
accessExport.DataTable = this.dataGridView1.DataSource as DataTable;
accessExport.DatabaseName = #"..\..\ToMdb.mdb";
accessExport.TableName = "ExportFromDatatable";
accessExport.SaveToFile();
}
and Here a link where you can find more clarification
Here I am not export gridview in MS Access but I made a database in MS Access by using C# with the help of this code:
ADOX.Catalog cat = new ADOX.Catalog();
ADOX.Table table = new ADOX.Table();
//Create the table and it's fields.
table.Name = "Table1";
table.Columns.Append("PartNumber", ADOX.DataTypeEnum.adVarWChar, 6); // text[6]
table.Columns.Append("AnInteger", ADOX.DataTypeEnum.adInteger, 10); // Integer
try
{
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=d:/m2.accdb;" + "Jet OLEDB:Engine Type=5");
cat.Tables.Append(table);
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0;" + "Data Source=d:/m2.accdb");
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Table1([PartNumber],[AnInteger]) VALUES (#FirstName,#LastName)";
cmd.Parameters.Add("#FirstName", OleDbType.VarChar).Value = "neha";
cmd.Parameters.Add("#LastName", OleDbType.VarChar).Value = 20;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
result = false;
}
cat = null;
Yes I tell you to all of you that we don't need to export data by gridview to MS Access , we can do this directly create database in MS Access using C#
I am importing excel data into sql server using SqlbulkCopy, but the problem is i want to prevent any duplicate records being entered. Is there a way by which duplicate can be ignored or deleted automatically?
protected void Button1_Click(object sender, EventArgs e)
{
string strFileType = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
string strFileName = FileUpload1.PostedFile.FileName.ToString();
FileUpload1.SaveAs(Server.MapPath("~/Import/" + strFileName + strFileType));
string strNewPath = Server.MapPath("~/Import/" + strFileName + strFileType);
string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strNewPath + "; Extended Properties=Excel 8.0;");
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
var command = new OleDbCommand("Select ID,Data FROM [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=ARBAAZ-1B14C081;Initial Catalog=abc;Integrated Security=True";
con.Open();
DataTable dt1 = new DataTable();
string s = "select count(*) from ExcelTable";
string r = "";
SqlCommand cmd1 = new SqlCommand(s, con);
try
{
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
da1.Fill(dt1);
}
catch
{
}
int RecordCount;
RecordCount = Convert.ToInt32(cmd1.ExecuteScalar());
r = RecordCount.ToString();
Label1.Text = r;
con.Close();
int prv = Convert.ToInt32(r);
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "ExcelTable";
SqlBulkCopyColumnMapping mapping1 = new SqlBulkCopyColumnMapping("excelid", "id");
SqlBulkCopyColumnMapping mapping2 = new SqlBulkCopyColumnMapping("exceldata", "data");
bulkCopy.ColumnMappings.Add(mapping1);
bulkCopy.ColumnMappings.Add(mapping2);
bulkCopy.WriteToServer(dr);
}
con.Open();
DataTable dt = new DataTable();
s = "select count(*) from ExcelTable";
r = "";
SqlCommand cmd = new SqlCommand(s, con);
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
catch
{
}
RecordCount = Convert.ToInt32(cmd.ExecuteScalar());
r = RecordCount.ToString();
Label1.Text = r;
con.Close();
int ltr = Convert.ToInt32(r);
if (prv == ltr)
{
Label1.Text = "No records Added";
}
else
{
Label1.Text = "Records Added Successfully !";
}
}
}
}
Can this problem be fixed by creating a trigger to delete duplicates? if yes how? i am a newbie i have never created a trigger.
Another problem is no matter what i try i am unable to get column mapping to work. I am unable to upload data when column names in excel sheet and database are different.
You can create INDEX
CREATE UNIQUE INDEX MyIndex ON ExcelTable(id, data) WITH IGNORE_DUP_KEY
And when you will insert data with bulk to db, all duplicate values will not inserted.
no, either you manage it on your dr object on you code before you load it into the db (like running a DISTINCT operation) or you create a trigger on the DB to check. The trigger will reduce the bulk insert's performace though.
Another option would be to bulk insert into a temp table and then insert into your destination table FROM your temp table using a select DISTINCT
as far as I remember,
you could filter out the redundant rows when importing from the excel file itself.
the following SQL query should be used in the OleDbCommand constructor.
var command = new OleDbCommand("Select DISTINCT ID,Data FROM [Sheet1$]", connection);