I am executing a sql query and storing it in a dataset, from there i am sending an email, everything works as expected, except for this time attached to the date 12:00:00 Am, it looks really weird on the email, i know that this occurs because the data type of that column is date and the object it gets attached to stores it as datetime and hence gets reset to midnight but i am querying sql directly and retrieving the value from the datatable but it still has the time attached to it. anyways to fix this issue i tried the below but it wont work:
string conn = ConfigurationManager.ConnectionStrings["WorkOrderConnectionString3"].ToString();
SqlConnection sqlconn = new SqlConnection(conn);
cmd.Connection = sqlconn;
sqlconn.Open();
cmd.CommandType = CommandType.Text;
String getdatasql = "SELECT WorkOrderNum, Requestor, Date, Department, CompletionDate, MachineDescription, MachineLocation," +
"[Type of Work Order], [Work Required], [WorkPerformed / PartsUsed], [Work Completed By :], [Maint. Supv. Approval]," +
" [Work Comp Date], [Supv Approval Date], Status, [Maint. Supv. Approval Date]" +
"FROM Master WHERE ([Type of Work Order] = N'General') AND (WorkOrderNum = #rockbottom) AND Status = 'Complete' ORDER BY WorkOrderNum DESC";
cmd.CommandText = getdatasql;
cmd.Parameters.AddWithValue("#rockbottom", TextBox10.Text);
SqlDataAdapter getdata = new SqlDataAdapter(cmd);
DataSet ds1 = new DataSet();
showdata.Fill(ds1);
string WorkOrderNum = ds1.Tables[0].Rows[0]["WorkOrderNum"].ToString();
string Requestor = ds1.Tables[0].Rows[0]["Requestor"].ToString();
string Date = ds1.Tables[0].Rows[0]["Date"].ToString();
String date = String.Format("{0:MM/d/yyyy}", Date);
cmd.ExecuteNonQuery();
When i did an debug i got this:
In my email it looks like this:
Tried the Solution still getting the time:
Got it Working :)
This is the problem:
string Date = ds1.Tables[0].Rows[0]["Date"].ToString();
Your Date variable is already a string, so trying to format that as if it's a DateTime isn't going to work. You want something like:
DateTime Date = (DateTime) ds1.Tables[0].Rows[0]["Date"];
... although I'd recommend against having a local variable named Date anyway, especially with a variable called date in scope as well...
Related
Simply I have an Excel file and I loaded it into SQL Server 2008.
I want to insert current date into the same cells added from Excel while date transferring... then date inserted automatically every time I added data and never lose old date. How can I do this?
string ssqltable = comboBox1.GetItemText(comboBox1.SelectedItem);
string myexceldataquery = "select * from [" + ssqltable + "$]";
try
{
OleDbConnection oconn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + imagepath + ";Extended Properties='Excel 12.0 Xml; HDR=YES;IMEX=1;';");
string ssqlconnectionstring = "Data Source=.;Initial Catalog=Bioxcell;Integrated Security=true";
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oconn);
oconn.Open();
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
DataTable dt = new DataTable();
dt.Load(oledbcmd.ExecuteReader());
bulkcopy.DestinationTableName = ssqltable;
for (int i = 0; i < dt.Columns.Count; i++)
{
bulkcopy.ColumnMappings.Add(i, i);
}
bulkcopy.WriteToServer(dt);
oconn.Close();
}
I used this but I know insert for only last record
I want to insert current date in newly created rows and doesn't lose previous columns date .. for example when i insert data each time insert new date saving old data with old date
SqlCommand Update6 = new SqlCommand("insert into Overseas (Date) Values('" + DateTime.Now.ToShortDateString() + "')", conn);
Update6.ExecuteScalar();
while using
SqlCommand Update6 = new SqlCommand("insert into Overseas (Date) Values (GETDATE())", conn);
Update6.ExecuteNonQuery();
the result was
enter image description here
So what's the solution ?
Set GETDATE() as the default constraint for your Date column of Overseas table.
SQL Command to add constraint:
ALTER TABLE Overseas
ALTER COLUMN Date DATETIME NOT NULL DEFAULT GETDATE()
Post this, you need not pass any value to this column while inserting. Just insert the remaining columns, this will get inserted automatically.
OR
Try this:
SqlCommand Update6 = new SqlCommand("insert into Overseas (Date) Values (GETDATE())", conn);
Update6.ExecuteScalar();
Based on your DB screenshot hope this query helps:
INSERT INTO Overseas (EnglishName,ProductCode,ProductName,TerritoryCode,TerritoryName,Salesvalue,CreditValue,NetSalesValue,Sales,Bonus,Bioxellbricks,BioxellTerritories,Date,ID)
SELECT EnglishName,ProductCode,ProductName,TerritoryCode,TerritoryName,Salesvalue,CreditValue,NetSalesValue,Sales,Bonus,Bioxellbricks,BioxellTerritories,GETDATE(),ID from [exceltablename]
Here Overseas is your DB table and exceltablename is your source table of excel.
You can simply use Datetime.Now(); function to get current date.
Also Use the zzz format specifier to get the timezone offset as hours and minutes. You also want to use the HH format specifier to get the hours in 24 hour format.
DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz")
Result:
2011-08-09T23:49:58+02:00
Some culture settings uses periods instead of colons for time, so you might want to use literal colons instead of time separators:
DateTime.Now.ToString("yyyy-MM-ddTHH':'mm':'sszzz")
Custom Date and Time Format Strings
Hope this will works for you .. Thank you
There is a function GETDATE() for this purpose.
Returns the current database system timestamp as a datetime value
without the database time zone offset. This value is derived from the
operating system of the computer on which the instance of SQL Server
is running.
https://learn.microsoft.com/en-us/sql/t-sql/functions/getdate-transact-sql
I am developing an Attendance Monitoring System and I need to compute the time difference between OutTime and InTime. The problem is I can't do it because the InTime value is in the Database, I can't seem to parameterize it. My query works with Access' query mode but not with C#. Here's my code for the time out button.
private void savetimeout()
{
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = #" UPDATE TimeinTimeout
SET OutTime = #1 AND HoursWorked = ROUND(([OutTime]-[InTime])*24,2)
WHERE EmployeeID = #2 AND InDate = #3";
command.Parameters.Clear();
command.Parameters.AddWithValue("#1", DateTime.Now.ToLongTimeString());
command.Parameters.AddWithValue("#2", textBox1.Text);
command.Parameters.AddWithValue("#3", DateTime.Now.ToShortDateString());
command.ExecuteNonQuery();
MessageBox.Show("Data Saved!");
this.Hide();
Form1 Mm = new Form1();
Mm.ShowDialog();
}
If I understand correctly, you have a field OutTime that you want to set with the current time and, in the same query, you want to calc the difference between the known value inside the field InTime and the current time.
You could use a query like this
command.CommandText = #"UPDATE TimeinTimeout
SET HoursWorked = #1-[InTime],
OutTime = #2
WHERE EmployeeID = #3 AND InDate = #4";
command.Parameters.Add("#1", OleDbType.Date).Value = DateTime.Now;
command.Parameters.Add("#2", OleDbType.Date).Value = DateTime.Now;
// Is this field really a string?
// If not use the appropriate type and convert the textbox.text
command.Parameters.Add("#3", OleDbType.VarWChar).Value = textBox1.Text;
command.Parameters.Add("#4", OleDbType.Date) = DateTime.Today;
command.ExecuteNonQuery();
Notice that to not confuse the database engine you should specify exactly what your parameters are. Using AddWithValue with DateTime field and passing a string creates a problem because your database engine needs to convert these strings back to datetime values and this conversion could produce unexpected problems. Always specify exactly the type of your parameters.
I tried to get result depending on two dates which the user checked.
I have two datetimepicker controls.
I want the user to chooses the "from" date and "to" date,
then the query get specific result.
leaving_time column type is nvarchar
This is my query:
SELECT name, mil_no, rotba, arrival_time, leaving_time, day, year
FROM dbo.Hodor_data
WHERE leaving_time BETWEEN '"+dateTimePicker1.Checked.ToString()+ "' AND '" + dateTimePicker2.Checked.ToString() + '"
Where is the mistake?
You should write parameterized queries and not using string concatenation for passing the parameters, in order to create a sql command. Using string concatenation makes you code vulnerable to sql injections.
var cmdText = #"SELECT ...
FROM dbo.Hodor_data
WHERE leaving_time BETWEEN #StartDate AND #EndDate";
var sqlCommand = new SqlCommand(cmdText, connection);
sqlCommand.Parameters.AddWithValue("#StartDate", dateTimePicker1.Value);
sqlCommand.Parameters.AddWithValue("#EndDate", dateTimePicker2.Value);
where connection is your sql connection object.
Try to use dateTimePicker1.Text in dateTimePicker1_ValueChanged event where you are using dateTimePicker2.Checked that return true or false not the value of date
Checked is a boolean property, and it is not the date. You need to use the Value Property. It is better to add parameters and explicitly specify the type so that the date format conflict is solved.
Edit: If column type in SQL server is NVARCHAR and of format MM/dd/yyyy, you need to use ONVERT(DATETIME, leaving_time, 101):
conn.Open();
SqlDataAdapter dataAdapter =
new SqlDataAdapter("SELECT name, mil_no, rotba, arrival_time, leaving_time, day, year "
+ "FROM dbo.Hodor_data where CONVERT(DATETIME, leaving_time, 101) "
+ "BETWEEN #p1 AND #p2", conn);
SqlParameter fromDate = new SqlParameter("#p1", SqlDbType.DateTime2);
fromDate.Value = dateTimePicker1.Value;
SqlParameter toDate = new SqlParameter("#p2", SqlDbType.DateTime2);
toDate.Value = dateTimePicker2.Value;
dataAdapter.SelectCommand.Parameters.Add(fromDate);
dataAdapter.SelectCommand.Parameters.Add(toDate);
DataTable dt = new DataTable();
dataAdapter.Fill(dt);
dataGridView1.DataSource = dt;
conn.Close()
You should really consider changing the type of column leaving_time to be a DateTime column. This will make your life easier in querying. I can't really see any advantage of storing these values as text.
I have a C# program and I want to run a MySQL query that insert a record. In this record I have a timestamp field that MUST BE the server timestamp, not the client timestamp.
So, I write this:
start_session = new MySqlDataAdapter("INSERT INTO CUBE_WORKTIME(ID_WORKTIME,
ID_RISORSA_FK,DATA,ORA_INIZIO_EVENTO, ORA_FINE_EVENTO,
ID_CDC_FK, CAUSALE, LAST_EVENT)
VALUES ('', '"+ idrisorsa_global + "', DATE(NOW()),NOW(),
NULL, '"+ IDCDC +"', 'Login', 'Y')", connection);
DataTable start_session_dataset = new DataTable();
start_session.Fill(start_session_dataset);
This query works well, the ID_RISORSA_FK and IDCDC fields are correct. But the date and the datetime are 0000-00-00 and 0000-00-00 00:00:00.
I also tried adding the quotes, but no effects.
Any ideas?
The first thing to change is the use of an MySqlDataAdapter to just insert a record. While this could work it is not the correct class to use for this work. A simple MySqlCommand is the correct object to use and with a lot less of infrastructure required
The second thing to change is the way in which you build your sql query. Do not concatenate together strings to form an sql command but use Parameters. This avoid Sql Injection and parsing problems.
So your code could be rewritten as
string cmdText = #"INSERT INTO CUBE_WORKTIME
(ID_RISORSA_FK,DATA,ORA_INIZIO_EVENTO, ORA_FINE_EVENTO,ID_CDC_FK,
CAUSALE, LAST_EVENT) VALUES (#risorsaID, CURDATE(), CURTIME(),
NULL, #cdcID, 'Login', 'Y')";
MySqlCommand cmd = new MySqlCommand(cmdText, connection);
cmd.Parameters.Add("#risorsaID", MySqlDbType.Int32).Value = idrisorsa_global;
cmd.Parameters.Add("#cdcID", MySqlDbType.Int32).Value = IDCDC;
int rowsInserted = cmd.ExecuteNonQuery();
I have a query which fetches the information from sql server on datematch.
I have searched a lot about SQL Server date string, I just want to match with the date and get the data from database. Also I am using SQL Server 2005, I want to fetch the date and take the time out of it?
Can anybody help me in that... I am new to C#
Here is my query.
return "select Timein, Timeout from Attendance where E_ID = " + E_ID + " and Date = " + DateTime.Now.ToShortDateString();
use the sql server CONVERT function to convert the input date param to time
Change your query to accommodate any one of the below CONVERT function
SQL query to convert Time format into hh:mm:ss:
select convert(varchar, <<dateparam>>, 108)
SQL query to convert Time format into hh:mi:ss:mmm(24h):
select convert(varchar, <<dateparam>>, 114)
You should always use parameters when querying a database - whether or not SQL injection is possible, it's just plain good practice to use parameters, and it solves some of the thorny how many quotes and which kind do I need here to make it a valid SQL statement questions, too.
So try something like:
string sqlStmt = "SELECT Timein, Timeout FROM dbo.Attendance " +
"WHERE E_ID = #ID AND Date = #Date";
using(SqlConnection conn = new SqlConnection("your-connection-string-here"))
using(SqlCommand cmd = new SqlCommand(sqlStmt, conn))
{
// set up parameters
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = E_ID;
cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = DateTime.Now.Date;
// open connection, read data, close connection
conn.Open();
using(SqlDataReader rdr = cmd.ExecuteReader())
{
while(rdr.Read())
{
// read your data
}
rdr.Close();
}
conn.Close();
}