I have a text file which has the date in the format dd-month-yyyy (example, 26-Dec-2014). That data is pulled into a database. I'm using SQLite and need to convert that date format into yyyy-MM-dd. The column in SQLite for the date is TEXT format for the date. I'm using it to put the value in a datagridviewer and eventually sorting it by date. Here is some of my code in C# that has the datetimepicker value converted to yyyy.MM.dd. and then the code to
string dt1 = From_date.Value.ToString("yyyy.MM.dd");
string dt2 = To_Date.Value.ToString("yyyy.MM.dd");
string stringsqlcommand = "SELECT * from CKData";
SQLiteDataAdapter sda = new SQLiteDataAdapter(stringsqlcommand, con);
sda.Fill(dt);
CKData is the data table. Is there a convert function like for traditional SQL where you can take the column from the table and make it a different format? The reason I'm using SQLite is because it's a local database which I will occasionally need access to and it has to be able to cross platforms easily (used on different computers).
Related
I'm trying to insert date value from DateTimePicker element in WinForms to a user defined method in the Table Adapter.
This is the function that gets data from the DateTimePicker element and inserts into the user defined method in the Table Adapter.
private void btn_searchRooms_Click(object sender, EventArgs e)
{
string checkIn = dtPicker_checkIn.Value.ToString("yyyy'/'MM'/'dd");
string checkOut = dtPicker_checkOut.Value.ToString("yyyy'/'MM'/'dd");
var dt = roomsTableAdapter.GetAvailableRooms(checkIn, checkOut);
dtGridView_availableRooms.DataSource = dt;
}
This is the user defined method in the Table Adapter that queries data from SQL server.
This is schema of the table that I'm querying data from
The method works fine without an issue but when I insert the date value from DateTimePicker to its parameter , it literally throws "Conversion failed " exception. The format of date is converted to "yyyy/MM/dd" to store it in the table with DATE data type column.
This is db fiddle for more information about the tables and data types that I'm storing db fiddle
How can I send date from C# to SQL Server in "yyyy/MM/dd" format?
Is there any workaround for this kind of issue?
While inserting date, you can use the following:
commmand.Parameters.Add("#Date", SqlDbType.Date).Value = dateTimePicker1.Value.Date;
#Date is a parameter. change it to your parameter name.
I have developed a web application to import Excel data into a SQL Server table using bulk copy column mapping. I used a select * from sheet query to copy the sheet data and insert into data table before writing it to table.
There are 20 columns in the sheet. The last column contains data of type datetime, string, integers and special characters. Its a mixed data type. When the application tried to copy and insert data into data table means it shows
Not a legal ole auth date
I have checked the last column values. Date value is correct only but it shows not a legal ole auth date issue.
Instead of using select * from sheet, is there any alternative approach like insert data into data table from Excel by row wise using for loop ?
Code is
OleDbConnection excelConnection1 = new OleDbConnection(excelConnectionString);
string query = string.Format("Select * from [{0}]", excelSheets[0]);
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection1))
{
dataAdapter.Fill(dt); **// issue raise when it try to fill the datatable**
}
I'm trying to import excel data to sql server database. Everything work fine except one column where the format in excel is was datetime and the datatype in my database was time. It was unable to convert datetime to time when i trying to insert the data.
My code was:
OleDbCommand exclCmd = new OleDbCommand("select * from [Sheet1$]", exclConnection);
exclConnection.Open();
OleDbDataReader exclReader = exclCmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "test_excel";
sqlBulk.ColumnMappings.Add("col1", "col1");
sqlBulk.ColumnMappings.Add("col2", "col2");
sqlBulk.ColumnMappings.Add("col3", "col3");
sqlBulk.ColumnMappings.Add("col4", "col4");
sqlBulk.WriteToServer(exclReader);
i tried to use "select con1, col2, col3, convert(time,col4) as col4 from [Sheet1$]" bt the convert function was not workable.
Anyone can help me on these? Thanks.
if staging table is an option, you could convert Excel date to string using TEXT(col4,"dd mmmm yyyy hh:mm:ss"). once the data is in staging table, you may write appropriate SQL statement to insert into correct table.
I would use SSIS for this kind of task since that gives more control on data transformations.
I'm working on an app that stores data in a spreadsheet to a Postgresql database. I'm familiar with C# and .Net but not so well with Postgresql. I'm having trouble storing a DateTime value into a TimeStamp column; I keep getting an error message: Failed to convert parameter value from a DateTime to a Byte[]. Any advice would be appreciated.
string query = "INSERT INTO organizer(organizer_name, contact_name, phone, alt_phone, created_date, last_update) " +
"VALUES('#name', '#contactname', '#phone', '#altphone', '#created', '#updated')";
OdbcCommand cmd = new OdbcCommand(query, con);
cmd.Parameters.Add("#name", OdbcType.VarChar);
cmd.Parameters["#name"].Value = org.Name;
cmd.Parameters.Add("#contactname", OdbcType.VarChar);
cmd.Parameters["#contactname"].Value = org.ContactName;
cmd.Parameters.Add("#phone", OdbcType.VarChar);
cmd.Parameters["#phone"].Value = org.Phone;
cmd.Parameters.Add("#altphone", OdbcType.VarChar);
cmd.Parameters["#altphone"].Value = org.AltPhone;
cmd.Parameters.Add("#created", OdbcType.Timestamp).Value = DateTime.Now;
cmd.Parameters.Add("#updated", OdbcType.Timestamp).Value = DateTime.Now;
con.Open();
cmd.ExecuteNonQuery();
I don't have a PostgreSQL db handy to test with, but I believe that you are seeing this because the OdbcType.Timestamp is actually a byte array, not a time and date. From MSDN:
Timestamp: A stream of binary data (SQL_BINARY). This maps to an Array of type Byte.
This is probably because the timestamp datatype, in SQL Server, is
a data type that exposes automatically generated, unique binary numbers within a database. timestamp is generally used as a mechanism for version-stamping table rows.
I would try using OdbcType.DateTime, which seems to map to the concept behind PostgreSQL's timestamp.
EDIT:
Here is a useful post which summarizes the mappings between PostgreSQL and .NET.
You've got a few solutions here...I'm going to assume the organizer table has the created_date and last_update as timestamp fields, correct? The silliest answer is to change those to varchar fields. heh.
2 better answers...I'm assuming this is a formatting error where DateTime.Now doesn't return in the format pgsql wants:
Since you are just giving it the current timestamp
you can define your table to default these columns to now() and then not pass values to this column, on an insert the table would just populate that with the default of now().
instead of defining the variable to DateTime.Now and then passing the variable, just send postgres now() and it will populate it in the format it feels right.
And second potential is to format the date into what PG expects as part of the insert statement...I'd need to know what DateTime.Now gives for a value to format it to what pg wants to see. This might be a bit of string manipulation...
I have got the following exception when try to select data from SQL Server or inserting data in in with a C# windows application. I am passing the date in where clause of select query in single quotes like this '16/03/2011' The exception message is shown below:
The conversion of a char data type to
a datetime data type resulted in an
out-of-range datetime value.
Is there any perfect solution for inserting and selecting date from sqlserver database irrelevant to the operating system. i.e. that works on both Italian and English OS.
If you can't use stored procs, or parameterized queries, you might want to format the date in a yyyy-mm-dd format. Ex. '2011-03-16'
T-SQL SAMPLE
INSERT INTO MyTable (SomeDate) VALUES ('2011-03-16')
or
SELECT * FROM MyTable WHERE SomeDate <= '2011-03-16'
Also, keep in mind the time portion of the date. If time is not important, then make sure you don't store it, because it could impact your SELECT queries down the road.
Use stored procedures, or parameterized queries. These will let you pass in a C# datetime object, and the conversion will be handled automatically for you.
I would suggest starting with the SQLDataAdapter class. A simple example of this would be:
using (SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM MyTable WHERE myDate = #myDate", someSqlConnection)
{
da.SelectCommand.Paramaters.Add("#myDate", new DateTime());
DataTable dt = new DataTable();
da.Fill(dt);
}
However, be aware that there are many different ways of achieving your goal. From your question, I would imagine you are creating SQL strings and executing them against your database. This is considered a Bad Practice for lots of reasons (including the one you describe). Read up about ORMs such as Entity Framework or NHibernate.