I am writing a program to interact with MSSQLLocal DB using C# through winforms but I find a problem witht the default datetime, it is not the date time format we use in my countr, I wonder how could I through Sql client -sql default C# classes I could change the default date format for a database or All the existing databases?
this could let me to format the datetime https://learn.microsoft.com/en-us/sql/t-sql/statements/set-dateformat-transact-sql?view=sql-server-ver15
but this doesnt change the default dateformat, how can i change programatically the DB datetime default format?
some code example
var connectionstr = $#"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog={DBname};Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
var con = new SqlConnection(connectionstr);
con.Open();
string changeDate = $#"SET DATEFORMAT dmy;";
SqlCommand command = new SqlCommand(changeDate , con);
var res = command.ExecuteNonQuery();
SqlCommand cmd = new SqlCommand(InsertCmd, con);
SqlDataAdapter adapter = new SqlDataAdapter() { InsertCommand = cmd };
adapter.InsertCommand.ExecuteNonQuery();
adapter.Dispose();
con.Close();
con.Dispose();
cmd.Dispose();
command.Dispose();
The datetime object in the database is just a datetime, the data can be set to a certain format when displaying in WinForm if you require it. For example, if i wanted the datetime to be display in the UK format:
DateTime.Now.ToString("dd/MM/yyyy")
Datetime Format
Turns out before adding a new value to the row you would need to include in the string CAST(01/01/2020) as dateformat
Related
I am new to C#, and learning. I have a SQL Server database where I have table record that has a column dob of data type date. I am trying to insert into dob from my textbox which has a value of 19-08-17 with the following code
datebox.Text = "19-08-17";
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand com = new SqlCommand(query, con);
string query= "insert into record (dob) values(#db)";
com.Parameters.AddWithValue("#db", datebox.Text);
com.ExecuteNonQuery();
But I get this error
Conversion failed when converting date and/or time from character string.
How can I solve this?
When you pass a variable to a DateTime column as a parameter, you need to convert the text to a DateTime variable before passing it:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].Connect ionString);
// Convert the textbox text to a DateTime variable
DateTime myDate = DateTime.ParseExact(datebox.Text, "dd-MM-yy", System.Globalization.CultureInfo.InvariantCulture);
SqlCommand com = new SqlCommand(query, con);
string query= "insert into record (dob) values(#db)";
com.Parameters.AddWithValue("#db", myDate);
com.ExecuteNonQuery();
I have a field date in DataTable
jeudi 12 mars 2015
vendredi 13 mars 2015
samedi 14 mars 2015
I need to store it in a table in sql server test which have a column datedes type date
SqlCommand command = new SqlCommand("INSERT INTO [test] ([Datedes]) VALUES('" + dt.Rows[i][j] + "')", con);
command.ExecuteNonQuery();
The code above always return error in conversion date.
how to resolve it ?
You need something like this:
Convert your rows[i][j] to a DateTime
use properly parametrized query in ADO.NET to insert your date
Code something like this:
// this might not work right now - you need to adapt this to that
// you can convert your strings like 'vendredi 13 mars 2015' to a
// valid "DateTime" object
DateTime dateTimeFromRow = Convert.ToDateTime(dt.Rows[i][j]);
// set up your DB connection string
string connectionString = "....";
// define your insert query with PARAMETERS
string insertQuery = "INSERT INTO [test]([Datedes]) VALUES(#DateDes);";
// use "using" blocks to properly dispose of connection and command
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(insertQuery, conn)
{
// define and set value for parameter
command.Parameters.Add("#DateDes", SqlDbType.Date);
command.Parameters["#DateDes"].Value = dateTimeFromRow;
// open connection, execute INSERT, close connection
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
In your example, you try to insert a string to your date type table column which is wrong obviously.
Depending on what you are doing;
Change your date typed column to nvarchar and insert that string
Parse your string to DateTime and insert that value with parameterized query.
For first option, just change your column type to nvarchar.
For second option, you need parse your string with fr-FR culture (if it is not your CurrentCulture) and pass this value directly.
var s = "samedi 14 mars 2015";
var dt = DateTime.Parse(s, CultureInfo.GetCultureInfo("fr-FR"));
using (var con = new SqlConnection(conString))
using (var cmd = con.CreateCommand())
{
cmd.CommandText = "INSERT INTO [test] ([Datedes]) VALUES(#date)";
cmd.Parameters.Add("#date", SqlDbType.Date).Value = dt;
con.Open();
cmd.ExecuteNonQuery();
}
What you are doing wrong is you try to parse data type string to datetime. And from your information the datetime format is not legal to parse. I suggest you to create another string type's field to store 'jeudi' 'vendredi' or 'samedi'.
Use to cut string :
var targetString = "jeudi 12 mars 2015";
var resultString = "";
int index;
foreach (var item in targetString)
{
if (int.TryParse(item.ToString(), out index) && !string.IsNullOrWhiteSpace(item.ToString()))
{
resultString = targetString.Substring(index);
}
}
//resultString == "12 mars 2015"
Afterthat use :
SqlCommand command = new SqlCommand("INSERT INTO [test] ([Datedes]) VALUES("#date")", con);
command.Parameters.AddWithValue(#date, resultString);
command.ExecuteNonQuery();
Do not append string like you do because it's not secure.
I develop an application in .Net C# that retrieves and insert data in a MySQL database.
To establish the connection I use MySqlConnection...
Inside my database, there is several tables each containing multiple date columns in format (yyyy-mm-dd hh: mm: ss)
My problem is that when I get columns by SQL request, my dates are in format (dd-mm-yyyy hh:mm:ss).
I could use the DateFormat() to format the columns, but there are a lot of columns date, and the request can change.
I would like to know if there is a way to impose a date format in the string MyConnection or something like that.
My string is:
string MyConnection = "datasource=192.168.0.1;port=3306;username=" + this.textBoxLogin.Text.ToString().Trim() +
";password=" + this.textBoxPassword.Text.ToString().Trim() + ";AllowZeroDateTime=True;TreatTinyAsBoolean=False;";
Queries + Getting Data + insertion in .xls file:
MySqlConnection conn = new MySqlConnection(MyConnection);
MySqlDataAdapter dataAdapter = new MySqlDataAdapter();
conn.Open();
dataAdapter.SelectCommand = new MySqlCommand("Select * From table;", conn);
MySqlCommandBuilder commandBuilder = new MySqlCommandBuilder(dataAdapter);
////get data
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
////insert in .xls File
DataSet dataSet = new DataSet();
dataSet.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dataSet.Tables.Add(dataTable);
CreateWorkbook("test\\Export.xls", dataSet);
Date format in Database: 2015/02/25 13:28:25
Date format in my .xls file: 25/02/2015 13:28:25
If the database stores the data in a date, datetime or timestamp data type, .NET will put that in a DateTime struct. This is perfectly fine since this is just the structure of the data, not the visual representation of it.
If you want to change the default date format of your program (which fixes it once for all for all dates), you can set the CurrentCulture to a culture that you require:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
If you just need to set the date format, you can set Thread.CurrentThread.CurrentCulture.DateTimeFormat and Thread.CurrentThread.CurrentUICulture.DateTimeFormat.
I'm trying to insert data of type 'date' from a textbox on my form to the database.
I want to ensure data entered by the user is stored in the format'dd/mm/yyyy' in the database. I have a column in the database of type 'date' but when i enter values of the format above, i get an exception (something like: cannot implicitly convert varchar to type date).
Please how do I convert date entered to the format 'dd/mm/yyyy'. I tried using CONVERT((varchar,getdate(),103) AS [DD/MM/YYYY]) but i cant figure out where to place it in my code. I'm new to c# and sql server, help please!!
It's better to not convert the date in SQL, and just pass it back as a date, and then within C# you can structure it however you want
myDate.ToString("dd/mm/yyyy")
use parameterised queries:
DateTime dt;
dt = DateTime.ParseExact(TextBox1.Text,
"dd/MM/yyyy",CultureInfo.InvariantCulture);
SqlCOnnection con=new SqlConnection("/*connection string here*/");
string query = "INSERT INTO [TABLENAME](DateCol) VALUES(#DateValue)";
SqlCommand cmd=new SqlCommand(query,con);
cmd.Parameters.AddWithValue("#DateValue",dt);
con.Open();
cmd.ExecuteNonQuery();
EDIT: from your comments :
i want the date to also be displayed in the same 'dd/MM/yyyy' format
in the database
You can can not control underlying Database how it displays or manages your Date in Database but if you want to get the date in format of dd/MM/yyyy while reading from database you can try the below:
SqlCOnnection con=new SqlConnection("/*connection string here*/");
string query = "SELECT [DateCol] FROM TABLENAME]";
SqlCommand cmd=new SqlCommand(query,con);
con.Open();
SqlReader reader = cmd.ExecuteReader();
while(reader.Read())
{
DateTime dt= Convert.ToDateTime(reader["DateCol"].ToString());
string mydateString = dt.ToString("dd/MM/yyyy");
}
con.Close();
I have 2 datetimepickers. In my select query i want to fetch records between these dates. datatype for date in database in varchar(MAX). For datetimepicker i have set custom format as dd-MM-yyyy. Here is my sql query
SqlDataAdapter da = new SqlDataAdapter("Select custname From tb_customer WHERE date >= '"+dtp_fromdate.Text+"' AND date <= '"+dtp_todate.Text+"'", con);
For eg: if my start date is 9-06-2012 and to date is 11-06-2012. With the above query it shows me record for 10-06-2012 and 11-06-2012
Incase if my start date is 10-06-2012 and to date is 11-06-2012. With the above query it shows me record for 10-06-2012 and not 11-06-2012
Please help
Use Convert or Cast T-SQL to convert VARCHAR value to Date or DateTime and also learn/use parameters instead of hard-coded SQL string.
The problem lies in lack of use of parameters. Using parameters will avoid any minsunderstanding between you and yuor database backend
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlDataAdapter da = new SqlDataAdapter();
string query = "Select custname From tb_customer WHERE date >= #from AND date <= #to"
da.SelectCommand = new SqlCommand(queryString, con);
da.SelectCommand.AddWithValue("#from" , dtp_fromdate.Value);
da.SelectCommand.AddWithValue("#to" , dtp_to.Value);
da.Fill(ds);
return ds;
}