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

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.

Related

How to create a new copy of an existing excel sheet(table) within an Excel File using nothing but OLEDB C# SSIS

I am trying to create a copy of an excel template that already currently exist in the excel document that is being worked on and inserted data into. The code is designed to take data from a table, insert it into specific cells of the Excel file, that have named highlighted columns above them so it is formated. I am using an SSIS script task to iterate through each row of data in the table. Once the data is inserted I am trying to create a copy of the template for the next row of data to be inserted.
//Foreach record set of data in table
//Insert data into the template into the specific cells
//Create new sheet for next iteration of data to be inserted
//end script
I can ONLY use System.Data.OleDb methods/library because the UAT and PROD servers can not accept additional libraries at this time. So the algorithm is setup like this. The Script is in a Foreach loop, so...
I expect it to create a copy of the current excel sheet it is inserting data into.
using (OleDbConnection ExcelConnection = new OleDbConnection(ExcelLocationConnectionString))
{
ExcelConnection.Open();
DataTableCollection TablesInFile = ExcelConnection.GetSchema("Tables").DataSet.Tables;
using (OleDbCommand InsertDataCommand = new OleDbCommand())
{
InsertDataCommand.Connection = ExcelConnection;
DataTable TableToInsertDataInto = TablesInFile[TablesInFile.Count];//Index could be out of range
if (YestAccountBranch == TodayAccountBranch)
AccountBranchChange = "No changes have been made to Account Branch.";
if (YestAccountType == TodayAccountType)
AccountTypeChange = "No changes have been made to Account Type.";
if (YestCostCenter == TodayCostCenter)
CostCenterChange = "No changes have been made to Cost Center.";
InsertDataSQL = "INSERT INTO [" + TableToInsertDataInto.ToString() + "$B5:F5:I5:L5:P5:T5:Y5:F2] VALUES('" + AccountNumber + "','" +
"" + CostCenterChange + "','" + AccountTypeChange + "','" + AccountBranchChange + "','" + TransactionLimit +
"','"+ DailyCumulativeLimit +"','" + BLCompanyID + "/" + ClientName + "','" + DateTime.Now.ToShortDateString().ToString() + "')";
InsertDataCommand.CommandText = InsertDataSQL;
InsertDataCommand.ExecuteNonQuery();
}
//Create table in excel sheet
using (OleDbCommand CreateTableCommand = new OleDbCommand())
{
CreateTableCommand.Connection = ExcelConnection;
string tableName = "AccountChange" + TablesInFile.Count.ToString() + 1;
CreateTableCommand.CommandText = $"CREATE TABLE [{tableName}]";
}
}

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.

Cant create Excel file using OLEDB 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.

how to insert a date from textbox to database

please help me to insert a date from a text box in dd-mm-yyyy format to sql server.
my code is as follows:-
int prio = Convert.ToInt32(Priority.Text);
string stdate = planstart.Text;
string endate= planend.Text;
string actst = actualstart.Text;
string acten = actualend.Text;
SqlConnection myconnection = new SqlConnection(constring);
SqlCommand mycommand = new SqlCommand();
DataSet mydataset = new DataSet();
SqlDataAdapter mydataadapter = new SqlDataAdapter();
myconnection.Open();
mycommand.Connection = myconnection;
mycommand.CommandText = " insert into project_status.dbo.Project_Status_Report values('" + projectcode.Text + "','" + projectname.Text + "',(select P_Code from project_status.dbo.Project_Type where Project_Type = '" + projecttype.Text + "')," + prio + ",'" + stdate + "','" + endate + "','" + actst + "','" + acten + "','" + currentstatus.Text + "','" + remark.Text + "','no');";
mycommand.CommandType = CommandType.Text;
mycommand.ExecuteNonQuery();
and it is throwing an exception saying:-
Conversion failed when converting date and/or time from character string.
You need to convert data according to you sql server formate that way you can resolve issue ..
Try
String UrDate = "27/12/2011";
System.Globalization.DateTimeFormatInfo dateInfo = new System.Globalization.DateTimeFormatInfo();
dateInfo.ShortDatePattern = "dd/MM/yyyy";
DateTime validDate= Convert.ToDateTime(toDate, dateInfo);
or
Format String For Dates
// String to DateTime
String MyString;
MyString = "1999-09-01 21:34 PM";
//MyString = "1999-09-01 21:34 p.m."; //Depends on your regional settings
DateTime MyDateTime;
MyDateTime = new DateTime();
MyDateTime = DateTime.ParseExact(MyString, "yyyy-MM-dd HH:mm tt",
null);
Make use of Paramerize query to avoid SQL INJECTION...make code less error pron
Walkthrough: Displaying Data in a Windows Form Using a Parameterized Query
Just a word of caution - you need to sanitize that query to prevent SQL injection attacks. Consider using parameterised queries. Read up about it, it's not really the scope of this answer.
You should create strongly typed DateTime objects first and then format them the way you need to insert. Consider the following modification to your code:
string stdate = DateTime.Parse(planstart.Text).ToString();
string endate = DateTime.Parse(planend.Text).ToString();
string actst = DateTime.Parse(actualstart.Text).ToString();
string acten = DateTime.Parse(actualend.Text).ToString();
EDIT
I removed the string parameter from the ToString() so you can get a valid DateTime string that's usable by SQL Server.
con.Open();
string query = "insert_demo";
/* date fromat Stored*/
TextBox2.Text = DateTime.Now.ToLongDateString();
SqlCommand com = new SqlCommand(query, con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Name", TextBox1.Text.ToString());
com.Parameters.AddWithValue("#Date", TextBox2.Text.ToString());
com.ExecuteNonQuery();

Visual studio 2008 datetimepicker to oracle date and timestamp

im trying to insert data into my oracle database but i am getting "invalid month" error as
it seems that i cant convert the datetimepicker value of my form into oracle date or timestamp(7) please help!
my code
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = " dd MM yyyy ";
string m = "insert into member(memberid,name,street,roadno,houseno,phoneno,joindate,sex) values(member_deptno.nextval,'" + a + "','" + b+ "','" + c + "','" + d + "','" + h + "','" + dateTimePicker1.Value.Date+ "','"+de+"')";
user parameterized sql insert.
e.g. parameterized select query
SqlConnection objConnection = new SqlConnection(connectionString);
objConnection.Open();
SqlCommand objCommand = new SqlCommand(
"SELECT * FROM User WHERE Name = #Name AND Password = #Password",
objConnection);
objCommand.Parameters.Add("#Name", tbName.Text);
objCommand.Parameters.Add("#Password", tbPassword.Text);
SqlDataReader objReader = objCommand.ExecuteReader();
As others have mentioned parameters are the way to go but I don't think they'll solve your issue.
I assume the CustomFormat shown in your snippet is the format Oracle wants. The problem is that when you call dateTimePicker1.Value.Date it gives you a DateTime object and since you're combining it with a string it executes the .ToString() method which results in a different format. You should put your format string in the .ToString() to control the output. Example:
dateTimePicker1.Value.Date.ToString("dd MM yyyy");

Categories