Showing Date only from SQL Database - c#

I am sending Date from WPF to ModelClass by this method.......
private void buttonNTSave_Click(object sender, RoutedEventArgs e)
{
ModelClass model = new ModelClass();
model.TaskInsertion(textBoxNTSubject.Text, textBoxNTType.Text, Convert.ToDateTime(datePickerNT.SelectedDate), textBoxNTTitle.Text, textBoxNTDetail.Text);
}
The Date is being inserted in database by this method...
public void TaskInsertion(string subject, string type, DateTime dueDate, string title, string detail)
{
SqlConnection conn = new SqlConnection(connectionString);
try
{
string query = "INSERT INTO Tbl_Task (Email, Subject, Type, DueDate, Title, Detail) VALUES ('" + userEmail + "', '" + subject + "' , '" + type + "', '" + dueDate.Date + "', '" + title + "', '" + detail + "')";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
conn.Close();
}
}
But Whenever I try to retrieve only Date from Database to a DataGrid, still the Time with Date is showing..
public DataTable OverDueCurrentTask()
{
SqlConnection conn = new SqlConnection(connectionString);
try
{
DateTime DateToday = DateTime.UtcNow.Date;
string query = "DECLARE #sDate Date SET #sDate = '" + DateToday.Date + "' SELECT Title, Subject, Type, DueDate FROM Tbl_Task WHERE DueDate >= #sDate";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter dataAdp = new SqlDataAdapter(cmd);
DataTable dataTbl = new DataTable("Tbl_Task");
dataAdp.Fill(dataTbl);
dataAdp.Update(dataTbl);
return dataTbl;
}
catch (Exception e)
{
conn.Close();
return null;
}
}
How to show Date without showing the Time?
N.B. In Database, DueDate is a Date Type column.

You need to cast DueDate column cast([DueDate] as date) > = #sDate. While sDate is already declared as date.
string query = #"DECLARE #sDate Date SET #sDate = '" + DateToday.Date + "'
SELECT Title, Subject, Type, cast([DueDate] as date) as DueDate FROM Tbl_Task
WHERE cast([DueDate] as date) >= #sDate";
Although it completes answer but you need to make subtle changes in the code, to avoid SQL injection attacks. Use SqlCommand Parameters. Add using blocks in the code.

I'm sure you can do this in C# as well. In the SQL query, you can use:
select cast([date] as date) as dateonly
To convert the datetime to a date.
The following Edit was provided by Dan Guzman:
The C# code to build the query string needed for the application is:
string query = "DECLARE #sDate Date SET #sDate = '" + DateToday.Date + "' SELECT Title, Subject, Type, CAST(DueDate AS date) AS DueDate FROM Tbl_Task WHERE DueDate >= #sDate;";

Related

textBox to DateTime in DB

Iam trying to get a DateTime out of an textBox, where it allready is in Format of MySql DateTime. The column in the DB is also DateTime format.
However, when i press my button to save the Dates in the DB, the whole row is gonna get emptyed.
I tried around with different formats und DataTypes in DB without anny effect
private void button4_Click(object sender, EventArgs e)
{
MySqlConnection conn = DBUtils.GetDBConnection();
conn.Open();
string startzeit = textBoxstartzeit.Text.ToString();
DateTime start = DateTime.Parse(startzeit);
string stopzeit = textBoxstopzeit.Text.ToString();
DateTime stop = DateTime.Parse(stopzeit);
string pstartzeit = textBoxstopzeit.Text.ToString();
DateTime pstart = DateTime.Parse(pstartzeit);
string pstopzeit = textBoxstopzeit.Text.ToString();
DateTime pstop = DateTime.Parse(pstopzeit);
MySqlCommand cmdnew = conn.CreateCommand();
cmdnew.CommandType = CommandType.Text;
cmdnew.CommandText = "UPDATE arbeitszeiten SET astart = '" + start + "', astop = '" + stop + "', pstart = '" + pstart + "', pstop = '" + pstop + "' WHERE id = '" + dataGridView.CurrentCell.Value + "'";
cmdnew.ExecuteNonQuery();
conn.Close();
}
private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
try
{
MySqlConnection conn = DBUtils.GetDBConnection();
conn.Open();
MySqlCommand feedstartzeit = conn.CreateCommand();
feedstartzeit.CommandText = "SELECT astart FROM arbeitszeiten WHERE id = '" + dataGridView.CurrentCell.Value + "'";
DateTime start = Convert.ToDateTime(feedstartzeit.ExecuteScalar());
textBoxstartzeit.Text = start.ToString("yyyy-MM-dd HH:mm:ss");
MySqlCommand feedstopzeit = conn.CreateCommand();
feedstopzeit.CommandText = "SELECT astop FROM arbeitszeiten WHERE id = '" + dataGridView.CurrentCell.Value + "'";
DateTime stop = Convert.ToDateTime(feedstopzeit.ExecuteScalar());
textBoxstopzeit.Text = stop.ToString("yyyy-MM-dd HH:mm:ss");
MySqlCommand feedstartpause = conn.CreateCommand();
feedstartpause.CommandText = "SELECT pstart FROM arbeitszeiten WHERE id = '" + dataGridView.CurrentCell.Value + "'";
DateTime startpause = Convert.ToDateTime(feedstartpause.ExecuteScalar());
textBoxstartpause.Text = startpause.ToString("yyyy-MM-dd HH:mm:ss");
MySqlCommand feedstoppause = conn.CreateCommand();
feedstoppause.CommandText = "SELECT pstop FROM arbeitszeiten WHERE id = '" + dataGridView.CurrentCell.Value + "'";
DateTime stoppause = Convert.ToDateTime(feedstoppause.ExecuteScalar());
textBoxstoppause.Text = stoppause.ToString("yyyy-MM-dd HH:mm:ss");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Bitte ID auswählen", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Button4 is the upload new data and the dataGridView part is filling the textBoxes with a preformated datetime that later get uploaded by button4
Your date time format should be your server date time format, if you want to use datetime then you should use datetime picker so you don't need to convert into datetime.
Allright, the by Jon Skeet suggested parametered sql request solved the problem.

Getting Date from database in a string

I am trying to get date from my database into a string and comparing it with the today's date to perform some operation.
What I did as a solution but still the label isn't displaying the messages.
if (FileUpload1.PostedFile != null)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//Save files to disk
FileUpload1.SaveAs(Server.MapPath("Files/" + FileName));
string FilePath = "Files/" + FileName;
//SqlCommand cmd = new SqlCommand();
DAL obj = new DAL();
using (SqlConnection conn = obj.openCon())
{
String sql = "Select DueDate from tbl_AssignmentUpload1 where AssignmentTitle like '" + AssignmentTitle + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader dr = cmd.ExecuteReader();
DateTime duedate = new DateTime() ;
if (dr != null && dr.HasRows)
{
while (dr.Read())
{
duedate = dr.GetDateTime(0);
}
dr.Close();
// now check if today greater than due date and update
if (duedate != null && today.Date > duedate)
{
sql = "Insert into tbl_AssignmentSubmit( Name ,AridNumber, Shift , Degree , Course , FileName ,FilePath ) values ('" + txt_Name.Text + "' , '" + txt_AridNumber.Text + "', '" + shift + "', '" + Degree + "', '" + Course + "','" + FileName + "','" + FilePath + "')";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
else
{
lbl_uploaded.Text = "Assignment can not be Submitted.You crossed the due date.";
}
}
}
}
You have to get DueDate from tbl_AssignmentUpload1 .
For example :
string strSQL = "Select DueDate from tbl_AssignmentUpload1 where AssignmentTitle like #AssignmentTitle ";
(SqlCommand myCommand = new SqlCommand(strSQL, cnn)) // Cnn is your sql connection
{
myCommand.Parameters.AddWithValue("#AssignmentTitle", AssignmentTitle );
using (SqlDataReader reader = myCommand.ExecuteReader())
{
while (reader.Read())
{
DateTime today1 = Convert.ToDateTime(reader["DueDate "].ToString());
}
}
}
After this you can do your insert statement
Try something like this. Ok updated with the fix for duedate.
using (SqlConnection conn = SQL.GeSQLConnection())
{
String sql = "Select DueDate from tbl_AssignmentUpload1 where AssignmentTitle like '" + AssignmentTitle + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader dr = cmd.ExecuteReader();
DateTime duedate = new DateTime();
if (dr != null && dr.HasRows)
{
while (dr.Read())
{
duedate = dr.GetDateTime(0);
}
dr.Close();
// now check if today greater than due date and update
if(duedate != null && DateTime.Today > duedate)
{
sql = "Insert into tbl_AssignmentSubmit( Name ,AridNumber, Shift , Degree , Course , FileName ,FilePath ) values ('" + txt_Name.Text + "' , '" + txt_AridNumber.Text + "', '" + shift +"', '" + Degree + "', '" + Course + "','" + FileName + "','" + FilePath + "')";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
else
{
lbl_uploaded.Text = "Assignment can not be Submitted.You crossed the due date.";
}
}
else
{
lbl_uploaded.Text = "No Due date was selected for the given assesment title";
}
}

Insert Date into sql table with Date column

Hello and thanks for reading.
I'm trying to insert the current date into my table, but I can't figure out how to write it correctly.
Here is my C# code:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString);
conn.Open();
string Comment = UserWriteComment.Text;
string ID = DetailedID.Text;
string Name = DetailedName.Text;
string UniqueID = lblID.Text;
string query = "INSERT INTO Comment(TicketID, Name, Comments, UserID, Date)" + "Values('" + ID + "', '" + Name + "', '" + Comment + "', '" + UniqueID + "', '" + Date + "')";
using (SqlCommand com = new SqlCommand(query, conn))
{
com.ExecuteNonQuery();
UserWriteComment.Text = "";
}
In the Query, There is a value called Date. This is here I like the Function to pass the current date into my Table.
I hope you can help me because I didnt managed to find the answer anywere.
Thanks:)
Use DateTime.Now or (in the database via sql) GetDate(). But more important, use sql-parameters to prevent sql-injection and conversion/localization issues:
string insertSql = #"INSERT INTO Comment(TicketID, Name, Comments, UserID, Date)
Values(#ID, #Name, #Comment, #UniqueID, #Date)";
using (var conn = new SqlConnection("...."))
using (var com = new SqlCommand(insertSql, conn))
{
com.Parameters.AddWithValue("#ID", ID);
com.Parameters.AddWithValue("#Name", Name);
com.Parameters.AddWithValue("#Comment", Comment);
com.Parameters.AddWithValue("#UniqueID", UniqueID);
com.Parameters.AddWithValue("#Date", DateTime.Now);
conn.Open();
com.ExecuteNonQuery();
}
The using-statement ensures that unmanaged resources like the connection will be disposed/closed even in case of an error.
Use DateTime.Now instead of Date. i.e. update the INSERT line to the following.
string query = "INSERT INTO Comment(TicketID, Name, Comments, UserID, Date)"
+ "Values('" + ID + "', '" + Name + "', '" + Comment + "', '"
+ UniqueID + "', '" + DateTime.Now + "')";
P.S: You really should be using Parameterize statements to avoid a Bobby Tables situation.
To fix this, implement it as shown by #Tim in his answer:
Instead of Date, try using the following
DateTime.Now
Another function that can help you is
GETDATE()
Date inserts for SQL Server is best used via :
GetDate()
or
Convert(Varchar, GetDate(), 101)
Note: converting the GetDate() value to varchar type 101 shortens the value to just the date w/o time stamp.

how to get data between two dates from sql server 2008 in asp.net

I'm using referenced date-picker control to select date. I get the error
Conversion failed when converting date and/or time from character string
public DataSet comsn(string x, DatePickerControl.DatePicker a, DatePickerControl.DatePicker b)
{
ConnectionStringSettings connectionstringsql = ConfigurationManager.ConnectionStrings["plprojectConnectionString"];
SqlConnection connectionsql = new SqlConnection(connectionstringsql.ConnectionString);
if (connectionsql.State != System.Data.ConnectionState.Open)
{
connectionsql.Open();
}
SqlCommand cmd = new SqlCommand("select a_id,commtyp,comm,primm,c_id,agent from comm where a_id= '" + x + "' AND date>= '" + a.CalendarDate + "' AND date <= '" + b.CalendarDate + "' ", connectionsql);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds, "comm"); //<------ At this line error occurred [ Conversion failed when converting date and/or time from character string ]
adp.Dispose();
return ds;
}
You can make this work by controlling the date format. When supplied to sql server as a string, I always format my data only string using 'YYYY-MM-DD', i.e., using the ToString('yyyy-MM-dd') on a date field.
However, you are better of turning your query into a parameter driven sql.
i.e., instead of "date >= '" a.Calendardate.ToString("yyyy-MM-dd")
Use "date >= #ADate"
and the supply the parameter value as
cmd.Parameters.Add("ADate", SqlDbType.DateTime).Value = a.Calendardate
I am assuming your datepicker has a "DateTime" property I am treating a.Calendardate as the DateTime property
You can avoid the exception and sql injection by using a parameterized query.
Replace:
SqlCommand cmd = new SqlCommand("select a_id,commtyp,comm,primm,c_id,agent from comm where a_id= '" + x + "' AND date>= '" + a.CalendarDate + "' AND date <= '" + b.CalendarDate + "' ", connectionsql);
With:
string sql = "select a_id,commtyp,comm,primm,c_id,agent from comm where a_id= #x AND date>= #a AND date <= #b "
var cmd = new SqlCommand(sql);
cmd.Parameters.Add("#x", SqlDbType.NVarChar, x);
cmd.Parameters.Add("#a", SqlDbType.DateTime, a);
cmd.Parameters.Add("#b", SqlDbType.DateTime, b);
cmd.Connection = connectionsql;

Insert DateTime into Sql Server 2008 from C#

I've been trying to get this right for over 2hrs so any help is highly appreciated
public void setAppointment(int studentID, DateTime appt)
{
connection.Open();
string sqlStatement3 = "UPDATE dbo.students SET appointmentDate = '" + appt.Date.ToString("yyyy-MM-dd HH:mm:ss") + "' WHERE ID = " + studentID + ";";
OleDbCommand updateCommand = new OleDbCommand(sqlStatement3, connection);
updateCommand.ExecuteNonQuery();
connection.Close();
}
So basically what that does is insert a datetime into an sql server table keeping the same format of the month and day to avoid regional settings getting in the way.
The only problem is that the time remains 00:00:00. Even though when I debug the code, 'appt' shows 28/06/2013 09:30:00
try below
public void setAppointment(int studentID, DateTime appt)
{
connection.Open();
string sqlStatement3 = "UPDATE dbo.students SET appointmentDate = ? WHERE ID = ?";
OleDbCommand updateCommand = new OleDbCommand(sqlStatement3, connection);
updateCommand.Parameters.AddWithValue("#p1", appt);
updateCommand.Parameters.AddWithValue("#p2", studentID);
updateCommand.ExecuteNonQuery();
connection.Close();
}
BUT!
You say it is sql server but why you using OleDbCommand ?
try below if it is sql server
public void setAppointment(int studentID, DateTime appt)
{
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "UPDATE dbo.students SET appointmentDate = #appointmentDate WHERE ID = #ID";
con.Open();
cmd.Parameters.AddWithValue("#appointmentDate", appt);
cmd.Parameters.AddWithValue("#ID", studentID);
cmd.ExecuteNonQuery();
}
}
Line 5.
Change
... appt.Date.ToString(...
to
... appt.ToString(...
I hope you have solved your problem from previous post and I agree SQL Statements to be used with parameters.
If you have an application date time format is fixed, then there is no harm in hard-coding but it would be good code to get date time format from your web.config file. This will help your code to be same consistent overall project.
Instead of
ToString("yyyy-MM-dd HH:mm:ss")
ToString(ConfigValue)
Too Late, But for your question : Try the code below.
public void setAppointment(int studentID, DateTime appt)
{
connection.Open();
string sqlStatement3 = "UPDATE dbo.students SET appointmentDate = '" + "CONVERT(datetime, '" + appt.Date.ToString("yyyy-MM-dd HH:mm:ss") + "', 103)" + "' WHERE ID = " + studentID + ";";
OleDbCommand updateCommand = new OleDbCommand(sqlStatement3, connection);
updateCommand.ExecuteNonQuery();
connection.Close();
}

Categories

Resources