Executing query by reading from excel cell - c#

Usually, we connect to an Oracle DB through C# and then execute queries through C#. But, I have an excel sheet. In that excel sheet, under F cell, I write my query in a cell. I have stored the value of this cell as strParam1. Declaration is as follows:
String strParam1 = Convert.ToString(xlRange.Cells[row, 6].Value);
I wish my program to read that cell and execute whatever query is written under that cell i.e. I want my code to read strParam1 and execute the query. How is fetching and executing query statements done using excel sheet here?
Posting my code
public void UpdateDatabase()
{
System.Data.OracleClient.OracleConnection conn = new System.Data.OracleClient.OracleConnection();
conn.ConnectionString = "Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.5.144)(PORT = 1521))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = orcl)));UID=mwm;PWD=mwm";
conn.Open();
OracleCommand command = conn.CreateCommand();
command.CommandText = "Select * from \"Task\"";
command.ExecuteNonQuery();
command.Dispose();
}

If I've understood your question, which seems so simple that I think I've not, this is all you're trying to do
public void UpdateDatabase()
{
System.Data.OracleClient.OracleConnection conn = new System.Data.OracleClient.OracleConnection();
conn.ConnectionString = "Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.5.144)(PORT = 1521))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = orcl)));UID=mwm;PWD=mwm";
conn.Open();
OracleCommand command = conn.CreateCommand();
command.CommandText = strParam1;
command.ExecuteNonQuery();
command.Dispose();
}

Related

SQL Bulk DestinationTableName

I use a .csv file to bulk insert into my SQL Server database. The problem is DestinationTableName because when I use a string for DestinationTableName, I get error exception
System.InvalidOperationException: Cannot access destination table
as you can see in the screenshot.
If a use "test" like copy.DestinationTableName = "test"; it works fine
string symbolName = dt.Rows[1][0].ToString();
string strConnection = #"Data Source =.\SQLEXPRESS; AttachDbFilename = C:\USERS\JEF\DOCUMENTS\DATABASE1.MDF; Integrated Security = True; Connect Timeout = 30; User Instance = True";
SqlConnection condb2 = new SqlConnection(strConnection);
string createTablerow ="create table ['"+symbolName+"'] (code1 VARCHAR(100) COLLATE Arabic_CI_AI_KS_WS,date1 varchar(50),open1 varchar(50),high1 varchar(50),low1 varchar(50),close1 varchar(50),vol1 varchar(50))";
using (SqlConnection connection = new SqlConnection(strConnection))
{
SqlCommand command1 = new SqlCommand(createTablerow, connection);
connection.Open();
command1.ExecuteNonQuery();
}
using (SqlConnection cn = new SqlConnection(strConnection))
{
cn.Open();
using (SqlBulkCopy copy = new SqlBulkCopy(cn))
{
copy.ColumnMappings.Add(0, "code1");
copy.ColumnMappings.Add(1, "date1");
copy.ColumnMappings.Add(2, "open1");
copy.ColumnMappings.Add(3, "high1");
copy.ColumnMappings.Add(4, "low1");
copy.ColumnMappings.Add(5, "close1");
copy.ColumnMappings.Add(6, "vol1");
copy.DestinationTableName = symbolName;
copy.WriteToServer(dt);
}
}
Just like you did when you created the table:
"create table ['"+symbolName+"']
the trick here is probably to escape the table name to compensate for the hyphen in it, so:
copy.DestinationTableName = "[" + symbolName + "]";
Note: if possible, it is usually preferable to stick to names that don't need escaping. But... if it works.

How to Insert Rows to Table Object Inside an Excel Sheet?

I have difficulties trying to insert rows into an existing table object. Here is my code snippet:
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + #"C:\myExcelFile.xlsx" + ";Extended Properties=\"Excel 12.0;ReadOnly=False;HDR=Yes;\"";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
string insertQuery = String.Format("Insert into [{0}$] (ID, Title,NTV_DB, Type ) values(7959, 8,'e','Type1')", TabDisplayName);
cmd.CommandText = insertQuery;
cmd.ExecuteNonQuery();
cmd = null;
conn.Close();
}
As a result I get my rows inserted below a ready-made table object:
I've also tried inserting data inside a table object like so:
string insertQuery = String.Format("Insert into [{0}$].[MyTable] (ID, Title,NTV_DB, Type ) values(7959, 8,'e','Type1')", TabDisplayName);
But I get an error:
The Microsoft Access database engine could not find the object 'MyTable'. Make sure the object exists and that you spell its name and the path name correctly. If 'MyTable' is not a local object, check your network connection or contact the server administrator.
As you can see, table with a name MyTable does exist. I would be very grateful if someone can shed some light on this mystery.
If you are using the Microsoft.ACE.OLEDB provider, then be aware that it doesn't support a named range. You need to provide the name of the sheet [Sheet1$] or the name of the sheet followed by the range [Sheet1$A1:P7928].
If the range is not provided, it will then define the table as the used range, which may contains empty rows.
One way to deal with empty rows would be to delete them, but the driver doesn't support the DELETE operation.
Another way is to first count the number of rows with a non empty Id and then use the result to define the range of the table for the INSERT statement:
using (OleDbConnection conn = new OleDbConnection(connectionString)) {
conn.Open();
string SheetName = "Sheet1";
string TableRange = "A1:P{0}";
// count the number of non empty rows
using (var cmd1 = new OleDbCommand(null, conn)) {
cmd1.CommandText = String.Format(
"SELECT COUNT(*) FROM [{0}$] WHERE ID IS NOT NULL;"
, SheetName);
TableRange = string.Format(TableRange, (int)cmd1.ExecuteScalar() + 1);
}
// insert a new record
using (var cmd2 = new OleDbCommand(null, conn)) {
cmd2.CommandText = String.Format(
"INSERT INTO [{0}${1}] (ID, Title, NTV_DB, Type) VALUES(7959, 8,'e','Type1');"
, SheetName, TableRange);
cmd2.ExecuteNonQuery();
}
}
If you execute this code:
var contents = new DataTable();
using (OleDbDataAdapter adapter = new OleDbDataAdapter(string.Format("Select * From [{0}$]", TabDisplayName), conn))
{
adapter.Fill(contents);
}
Console.WriteLine(contents.Rows.Count);//7938
you will see 7938 (last row number on your screenshot). And when you insert new row, it inserted at 7939 position. Empty content in (7929, 7930, ...) rows are ignored, because excel knows that last number is 7938.
Solutions:
You must delete all rows after 7928 in excel file.
You must insert on specific position.
I'm not sure Access C# works the same as Excel, but this worked on a spreadsheet for me. Maybe it could help you?
Table3.ListRows[1].Range.Insert(Excel.XlInsertShiftDirection.xlShiftDown);
Try this
private void GetExcelSheets(string FilePath, string Extension, string isHDR)
{
string conStr="";
switch (Extension)
{
case ".xls": //Excel 97-03
conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"]
.ConnectionString;
break;
case ".xlsx": //Excel 07
conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"]
.ConnectionString;
break;
}
//Get the Sheets in Excel WorkBoo
conStr = String.Format(conStr, FilePath, isHDR);
OleDbConnection connExcel = new OleDbConnection(conStr);
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
cmdExcel.Connection = connExcel;
connExcel.Open();
//Bind the Sheets to DropDownList
ddlSheets.Items.Clear();
ddlSheets.Items.Add(new ListItem("--Select Sheet--", ""));
ddlSheets.DataSource=connExcel
.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
ddlSheets.DataTextField = "TABLE_NAME";
ddlSheets.DataValueField = "TABLE_NAME";
ddlSheets.DataBind();
connExcel.Close();
txtTable.Text = "";
lblFileName.Text = Path.GetFileName(FilePath);
Panel2.Visible = true;
Panel1.Visible = false;
}

Getting Error while trying to update record in Ms Access 2007 using c#

Trying update record dont know why i am getting error
Exception Details: System.Data.OleDb.OleDbException: No value given for one or more required parameters.
this is my code please guide me.
public static string lasttable;
public static string newtable;
newtable = "c" + cont.ToString();
lasttable = input;
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\AGENTJ.AGENTJ-PC\Documents\Visual Studio 2010\WebSites\mfaridalam\App_Data\mfaridalam1.accdb; Persist Security Info=False;";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
string query = "UPDATE [LastInfo] SET [LastAlbum]=#newtable WHERE [LastAlbum]=#lasttable";
OleDbCommand comd = new OleDbCommand();
comd.Parameters.Add("#LastAlbum", OleDbType.VarChar);
comd.Parameters["#LastAlbum"].Value = newtable;
comd.CommandText = query;
comd.Connection = conn;
comd.ExecuteNonQuery();
conn.Close();
You are using OleDb and OleDb doesn't care about parameter names.
However you need to add a parameter for every placeholder present in the command text and in the same order in which they appear.
You have two parameter (#newtable and #lasttable) but you add just one parameter (and you name it wrongly, but, as I have said, that doesn't matter for OleDb).
You need to add the second parameter #lasttable
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\AGENTJ.AGENTJ-PC\Documents\Visual Studio 2010\WebSites\mfaridalam\App_Data\mfaridalam1.accdb; Persist Security Info=False;";
using(OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
string query = "UPDATE [LastInfo] SET [LastAlbum]=#newtable WHERE [LastAlbum]=#lasttable";
OleDbCommand comd = new OleDbCommand();
comd.Parameters.Add("#newTable", OleDbType.VarChar);
comd.Parameters["#newTable"].Value = newtable;
comd.Parameters.Add("#lastTable", OleDbType.VarChar);
comd.Parameters["#lastTable"].Value = lasttable;
comd.CommandText = query;
comd.Connection = conn;
comd.ExecuteNonQuery();
}

Executing SQl Queries in C# using CLR

I am using SQl CLR for parsing some table column. I want to execute the queries also in C# user defined function. Can somebody give an example to execute select and insert queries in the function?
Thank you in advance.
SqlConnection objSqlConn;
string connString = string.Empty;
connString = "Data Source=(local);Initial Catalog=DB;User ID=uname;pwd=pass;Password=pass";
objSqlConn = new SqlConnection(connString);
objSqlConn.Open();
string query = "Select count(*) FROM [DB].[dbo].[TableName]";
SqlCommand cmdTotalCount = new SqlCommand(query, objSqlConn);
cmdTotalCount.CommandTimeout = 0;
string TotalCountValue = cmdTotalCount.ExecuteScalar().ToString();
return TotalCountValue;
In CLR, you can use existing connection to run queries.
Simple, returning data to client:
var cmd = new SqlCommand("select * from [table]");
SqlContext.Pipe.ExecuteAndSend(cmd);
Returning data via SqlDataReader:
var con = new SqlConnection("context connection=true"); // using existing CLR context connection
var cmd = new SqlCommand("select * from table", con);
con.Open();
var rdr = cmd.ExecuteReader();
SqlContext.Pipe.Send(rdr);
rdr.Close();
con.Close();
Running other commands:
var con = new SqlConnection("context connection=true"); // using existing CLR context connection
var cmd = new SqlCommand("insert into [table] values ('ahoj')", con);
con.Open();
var rsa = cmd.ExecuteNonQuery();
con.Close();
Once you switch to C# you execute queries like you'd normally do from your application (using ADO.NET's SqlConnection and SqlDataReader, using LINQ to SQL or using your custom build data layer).
To connect with the database you have to mention the database username and password in the connection string of your web.config file.

Reading Excel in .NET, how to get specific rows?

I have got the following code from here to read an Excel file using C# .NET:
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Book1.xls;Extended Properties=""Excel 8.0;HDR=YES;""";
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
DbCommand command = connection.CreateCommand()
command.CommandText = "SELECT City,State FROM [Cities$]";
I want to select only 10 rows starting from the 4th row, how can I do that?
I'm no Excel querying expert, but this certainly works. Use TOP to limit the query to 13 rows. The first row is the header with column names so it may not count. Obviously change if I misunderstand. Then, keep track of a row ID and do stuff to rows on or after 4.
Hope this helps!
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Book1.xls;Extended Properties=""Excel 8.0;HDR=YES;""";
using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(connectionString)) {
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT top 13 City,State FROM [Cities$]";
conn.Open();
System.Data.IDataReader dr = cmd.ExecuteReader();
int row = 2;
while (dr.Read()) {
if (row++ >= 4) {
// do stuff
Console.WriteLine("{0}, {1}", dr[0], dr[1]);
}
}
}

Categories