Include milliseconds in sql query from C# - c#

I am currently using SqlDataAdapter to query a SQL database:
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = myConnection;
string cmd = #"select * from dbo.Table where errordate > '2015-05-29'";
myConnection.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd, sqlConn);
da.Fill(dt);
The query is working fine but the only problem is that The date column does not include milliseconds. When I perform the same query with MS SQL server management studio, the milliseconds are there. Why wouldn't the milliseconds be present in C#?
Thanks

After reading the comments above I realized the issue was not with the SQL query but with the way I accessed the data from the DataTable. This did the trick:
DateTime date = (DateTime)dr[2];
string ds = date.ToString("MM/dd/yy HH:mm:ss.fff");

Cast your datetime variable to a string using
[YourDate].ToString("MM/dd/yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture);

Related

How could I configure the MSSQLLocal default datetime format

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

DataTable not showing minutes and seconds

string command = "select x,y,z,t,ModifiedDate " +
" from ZZ where PP='" + XX + "' and Type='" + YY + "' order by ModifiedDate";
connection();
SqlCommand command = new SqlCommand(command, con);
command.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
ModifiedDate is a DateTime - in SQL i see "2019-07-23 12:02:35.283"
But when i want to see "dt" in C# i only see "2019-07-23"
how can i see full time with minutes and seconds?
The type of the column in the DataTable is DateTime. ZZ is a table.
You could try setting the row to something like this:
((DateTime)row[0]).ToString("yyyy-MM-dd HH:mm:ss")
Like how you said in the comments just add the formatting to your ToString() when assigning to the variable.
What you had shouldn't even compile, since you can't declare both a string and an SqlCommand object with the same name in the same scope. Run the query like this:
string sql = #"
select x,y,z,t,ModifiedDate
from ZZ
where PP= #XX and Type= #YY
order by ModifiedDate";
DataTable dt = new DataTable();
// .Net connection pooling means you really do want a new connection object most of the time. Don't try to re-use it!
// The "using" blocks make sure your objects are closed and disposed, even if an exception is thrown
using (var con = new SqlConnection("connection string here"))
using (var cmd = new SqlCommand(sql, con))
using (var da = new SqlDataAdapter(cmd))
{
//use the actual column types and lengths from your database here
cmd.Parameters.Add("#XX", SqlDbType.NVarChar, 30).Value = XX;
cmd.Parameters.Add("#YY", SqlDbType.NVarChar, 10).Value = YY;
da.Fill(dt);
}
But this still won't fix everything. It's mainly about closing the huge gaping-wide security hole and potential denial-of-service issue in the original code.
The actual issue from the question is in a different place than this code. The time portion of your ModifiedDate column is in the resulting DataTable. Really. I promise. If you don't see it, it's because of a DataView, format string, or other issue at the point where you try to observe or display these results.
There is no Date class in C# - even DateTime.Date() returns another DateTime object with an all zeros time component.
Your problem sounds very much like a Regional Settings issue, or more specifically, CultureInfo in C#. Your default (or "current" as applied by Thread.CurrentThread's CurrentCulture or CurrentUICulture) has its CultureInfo.DateTimeFormat setup to supply date-without-time formatting.
Probably the FullDateTimePattern is set to "yyyy-mm-dd" or something equivalent.

How to convert yyyy-mm-dd to yyyymmdd in where clause of SQL select command

The format in the database for date column is yyyymmdd but my code in aspx.cs passes the parameter value as yyyy-mm-dd. How can I convert yyyy-mm-dd to yyyymmdd in the WHERE clause if my select statement?
aspx.cs code:
adapter.SelectCommand = new SqlCommand("select distinct a.e_id from tenter where (date='" + Convert(DateTime.Value.ToString()) + "')", myConn);
Please don't save your DateTime values as a character.
Type your date column as a datetime or datetime2 and pass your DateTime.Now value directly to your parameterized queries. Otherwise, it will be open for SQL Injection attacks.
Read: Bad habits to kick : choosing the wrong data type
As an example;
using(var myConn = new SqlConnection(conString))
using(var cmd = myConn.CreateCommand())
{
cmd.CommandText = "select distinct a.e_id from tenter where date = #date";
cmd.Parameters.Add(#date, SqlDbType.DateTime2).Value = DateTime.Now;
using(var adapter = new SqlDataAdapter(cmd))
{
// Do your operations.
}
}
Also date might reserved word in future releases of SQL Server. You might need to use it as [date] as well.
It may helps you
You can use this logic and work on your query
declare #a date= '2014/2/3'
select replace(#a,'-','')
use SQL CAST()
SqlCommand cmd=new SqlCommand();
cmd.Connection=con;
cmd.CommandText="select distinct a.e_id from tenter where cast(date as date)=cast(#date as date)";
cmd.Paramenter.AddWithValue("#date",Convert.ToDateTime(DateTime.Value));
adapter.SelectCommand = new SqlCommand ("select distinct a.e_id from tenter where (date='" + DateTime.ParseExact(("2015-03-18"), "yyyy-MM-dd", null).ToString("yyyyMMdd") + "')", myConn);
Thank you very much to all of you.
The best answer for me like this:-
adapter.SelectCommand = new SqlCommand ("select distinct a.e_id from tenter where (date='" + startdate.Value.ToString().Replace("-",string.Empty) + "')", myConn);
Maybe simply : DateTime.Value.ToString().Replace("-",string.empty)
for mysql you can try this :
where date_format(date,'%Y%m%d') = '20150318'
#+jef

How to compare 2 dates taken from datetimepicker in select query?

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;
}

DataSet help in C#

I connected an sql database in c# and now trying to put the contents into a dataset. How will I be able to do that?
My code is:
string constr = "Data Source=ECEE;Initial Catalog=Internet_Bankaciligi;User ID=sa";
SqlConnection conn = new SqlConnection(constr);
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter("Select * from Internet_Bankaciligi", conn);
DataSet myDataSet = new DataSet();
DataRow myDataRow;
SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter);
mySqlDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
mySqlDataAdapter.Fill(myDataSet,"Internet_Bankaciligi");
myDataRow = myDataSet.Tables["IB_Account"].NewRow();
myDataRow["Account_ID"] = "NewID";
myDataRow["Branch_ID"] = "New Branch";
myDataRow["Amount"] = "New Amount";
myDataSet.Tables["Customers"].Rows.Add(myDataRow);
the line: "mySqlDataAdapter.Fill(myDataSet,"Internet_Bankaciligi");" gives an error as 'Invalid object name 'Internet_Bankaciligi'.' but Internet_Bankaciligi is my database name.
Also if i use:
SqlCommand selectCMD = new SqlCommand("select (*) from IB_Account", conn);
SqlDataAdapter myAdapter = new SqlDataAdapter();
myAdapter.SelectCommand = selectCMD;
myAdapter.Fill(myDataSet);
then: "SqlCommand selectCMD = new SqlCommand("select (*) from IB_Account", conn);" gives an error saying invalid syntax. How will I get it correct?
If "Internet_Bankaciligi" is your actual database name, then you can't execute a SQL command directly against it. You have to change your SQL to select from a table or a view.
Your second example doesn't work because "SELECT (*)" is not valid syntax. It should be "SELECT * FROM IB_Account"... no parentheses.
I checked this statement in Sql Server 2008:
Select (*) from <table>
It doesn't work. I never seen this syntax, not in sqlserver 2005, nor Oracle nor sqlite.
try this one:
Select * from <table>
Edit: If I were you I will try using strongly typed datasets, or even Entity Framework which both are more advance and easier to work with. Google them.

Categories

Resources