Cant create Excel file using OLEDB C# - c#

string TempFileLocation="Filelocation";
string tempfilename ="FileName";
string TabName ="TabName";
string xConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" +TempFileLocation+ tempfilename +".xls;Extended Properties='Excel 8.0;HDR=YES'";
var conn = new OleDbConnection(xConnStr);
string ColumnName ="[columename] varchar(255)"
conn.Open();
var cmd = new OleDbCommand("CREATE TABLE [" + TabName + "] (" + ColumnName + ")", conn);
cmd.ExecuteNonQuery();
conn.Close();
I using above code to create the table but it did not allow me to create ColumnName with more than 64 characters. Please give me soluition for this problem.

The column name cannot be over 64 characters.
According to MSDN:
Maximum column name length:
Column names over 64 characters will produce an error.

Related

Excel update query putting all data in row 1

I'm using an oledbconnection to connect to an excel spreadsheet
Connection string:
string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" +
Request.PhysicalApplicationPath + "tmp\\" + Session["Id"] + ".xlsx;" + "Extended Properties=\"Excel 8.0;HDR=NO;\"";
Update query:
cmdUpdate = new OleDbCommand("UPDATE [Contributions$B6:B6] SET F1 = 'value'", excelConn);
However, the data is being set in cell B1, not B6. All other queries are also adding the data in row 1, but the correct column...any ideas?

Reading string as date from csv files in c# Windows Application

I'm exporting a CSV file into a datatable. Exporting is working fine. The provider using is Microsoft.ACE.OLEDB.12.0
The issue is that I have a column with date which contains date in string along with single quots, I removed the single quote, the date format is like this: "2015-05-02 12:57:43.888"
I need to convert this date to dd/MM/yyy format.
I tried using convert function, but it's showing error
Undefined function convert in expression
Since I need to filter the csv file based on date, I need to convert the date from csv itself.
My code is as follows:
string header = isFirstRowHeader ? "Yes" : "No";
string pathOnly = Path.GetDirectoryName(path);
string fileName = Path.GetFileName(path);
string sql = #"Select * From " +
" (SELECT ['TRANSACT'] AS InvNo,['TIMESTART'] AS InvDate,['STATUS'] AS InvStatus,['NETTOTAL'] AS InvNet ,['FINALTOTAL'] " +
" AS InvFinal,REPLACE(['TIMESTART'],'''','') as TIMESTART FROM [" + fileName + "]) Table1 " +
" WHERE convert(varchar(10),TIMESTART,103) between '" + strFrom + "' and '" + strTo + "'";
using (OleDbConnection connection = new OleDbConnection(
#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathOnly +
";Extended Properties=\"Text;HDR=" + header + "\""))
using (OleDbCommand command = new OleDbCommand(sql, connection))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
adapter.Fill(dataTable);
}
Try using this code:
var sDate = "2015-05-02 12:57:43.888";
DateTime date = new DateTime();
DateTime.TryParse(sDate, out date);
Console.WriteLine(date.ToString("dd/MM/yyyy"));
Or take a look here .NET Fiddle
I found the answer.
Since I'm using the Microsoft.ACE.OLEDB driver to load the csv sheet via Provider=Microsoft.ACE.OLEDB.12.0 I have to use the query formatting and functionality available within MS Access.

Importing .DAT file to Database?

How would I go about import/inserting a .DAT file into the database by calling a procedure?
Here's what my file would look like and it has to go into the database in this format.
50 4411902304 1 3 441192304 01/02/2013
Would the process be the same for .DAT file as to xml file?
Here's what I have for xml
SqlConnection myConnection = new SqlConnection("user id=name;" +
"password=password;server=servername;" +
"Trusted_Connection=yes;" +
"database=database; " +
"connection timeout=30");
var conn = new SqlConnection();
conn.ConnectionString = "user id=idName;" +
"password=password;" + "server=servername;" + "Trusted_Connection=yes;" + "database=databasename; " + "connection timeout=30";
string filePath = "C:/TestData2.xml";
string xml = File.ReadAllText(filePath);
using (SqlConnection con = new SqlConnection(conn.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("procedureName"))
{
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#x", xml);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("done");
}
}
What happens is that XML is a new technology compared to the old flat file (DAT).
XML is a markup format file and there are functions implemented to make easier the importing tasks.
Flat file are older, so a different approach is needed.
You can use the bcp (bulk copy program) to import files to SQL Server or the SSIS Import options.
Or, you can also use:
System.IO.StreamReader file = new System.IO.StreamReader(#"c:\data\TestData2.dat");
int counter = 0;
while ((line = (file.ReadLine())) != null){...}
And parsing each line using the Split command.
string[] fields= line.Split(' ');
string a = fields[0];
string b = fields[1];
string c = fields[2];
and then execute a command to insert each line:
string sqlCommandtoInsert= "INSERT INTO [Table] (Tablefield1, Tablefield2, Tablefield3) VALUES (" + a + ", " + b + ", '" + c + "');";
cmd.CommandText = sqlCommandtoInsert;
cmd.ExecuteNonQuery();
Inserting each record in your table.

OleDB Connection String to MySQL Connection String

I have this OleDB code which basically reads an excel file and displays it on to the datagridview after a button click:
string pathConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txtPath.Text + ";Extended Properties=\"Excel 8.0;HDR=Yes;\";";
OleDbConnection conn = new OleDbConnection(pathConn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("SELECT * FROM [" + txtSheet.Text + "$]", conn);
DataTable dt = new DataTable();
myDataAdapter.Fill(dt);
dgvViewDrivers.DataSource = dt;
My question is that how would I make a MySQL Connection out of this OleDB connection string? Please help me.
You need to use MySQL .NET connector
http://dev.mysql.com/downloads/connector/net/
using (MySqlConnection conn = new MySqlConnection("SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";"))
{
using (MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "sql here";
cmd.ExecuteNonQuery();
}
}
Your current code
This
using (vDBCon = new MySqlConnection("SERVER=localhost;Data Source=" + txtPath.Text + ";user=root;PASSWORD= ;"))
txtPath.Text needs to be the name of your database in MySQL. I assume you left the password out. If not you need one.
"SERVER=localhost;Data Source=MyDatabase;user=root;PASSWORD=MyPassword;"
where MyDatabase is the actual name of your database and MyPassword is the password you use to login with
You have to actually be running MySQL Server itself to create and connect to a MySQL database. it doesn't work of a file like Access. If you want something like that just use SQLite.
this
vCmd.CommandText = "SELECT * FROM [" + txtSheet.Text + "$]";
this you will be selecting data from your table in MySQL so it needs to look like
vCmd.CommandText = "SELECT * FROM MyTable";
where MyTable is actually the name of your table in the database

get column names from a table where one of the column name is a key word

Im using c# .net windows form application. I have created a database which has many tables. In one of the tables I have entered data. In this table I have 4 columns named key, name,age,value. Here the name "key" of the first column is a key word. Now I am trying to get these column names into a combo box. I am unable to get the name "key".
It works for "key" when I use this code:
private void comboseccolumn_SelectedIndexChanged(object sender, EventArgs e)
{
string dbname = combodatabase.SelectedItem.ToString();
string path = #"Data Source=" + textBox1.Text + ";Initial Catalog=" + dbname + ";Integrated Security=SSPI";
//string path=#"Data Source=SYED-PC\SQLEXPRESS;Initial Catalog=resources;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(path);
string tablename = comboBox2.SelectedItem.ToString();
//string query= "Select * from" +tablename+;
//SqlDataAdapter adp = new SqlDataAdapter(" Select [Key] ,value from " + tablename, con);
SqlDataAdapter adp = new SqlDataAdapter(" Select [" + combofirstcolumn.SelectedItem.ToString() + "]," + comboseccolumn.SelectedItem.ToString() + "\t from " + tablename, con);
DataTable dt = new DataTable();
adp.Fill(dt);
dataGridView1.DataSource = dt;
}
This is beacuse I am using "[" in the select query. But it wont work for non keys. Or if I remove the "[" it is not working for key . Please suggest me so that I can get both key as well as nonkey column names.
Just enclosed them in square bracket:
select [key] from tbl
Or if you want your code to be ANSI-compliant, use double quote:
select "key" from tbl
Try this if this will work:
SqlDataAdapter adp = new SqlDataAdapter(" Select \"" + combofirstcolumn.SelectedItem.ToString() + "\"," + comboseccolumn.SelectedItem.ToString() + "\t from " + tablename, con);
Value is also a keyword in MSSQL. I would have thought that you would have to wrap this in [] too.
Try using Alias for the "key" column.
For E.g: Select Key as Keyword ,value as KeywordValue ...

Categories