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();
}
Related
Combobox items binding in database:
using (MySqlConnection connect = new MySqlConnection(connectionString))
{
string sql = "SELECT DISTINCT tedavi_tarih FROM " + mw.db_name + ".tedavi Where hasta_id= '" + mw.hasta_id + "' ORDER BY tedavi_tarih DESC";
using (MySqlCommand cmd = new MySqlCommand(sql, connect))
{
connect.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
combobox_tarih.Items.Add(reader.GetString("tedavi_tarih"));
}
connect.Close();
}
}
tedavi_tarih format is Date but when I add it to combobox, it displays as "5.01.2018 00:00:00". I want to display only "5.01.2018". I tried this in XAML:
ItemStringFormat="dd/M/yyyy"
It doesn't work. How can I fix it?
reader.GetString("tedavi_tarih") returns a string. It doesn't return a DateTime. A string doesn't become a DateTime when you try to convert it to a string using a DateTime format string.
If the "tedavi_tarih" column really is Date, this should work:
while (reader.Read())
{
combobox_tarih.Items.Add(reader.GetDateTime("tedavi_tarih"));
}
If by "format as Date" you really mean that it's a date formatted as a string, you'll have to use DateTime.TryParse(). Let me know.
Obligatory warning: The code below is a SQL injection vulnerability. It is very bad, very dangerous practice. You should not concatenate SQL strings. You should use SqlParameters instead.
string sql = "SELECT DISTINCT tedavi_tarih FROM " + mw.db_name + ".tedavi Where hasta_id= '"
+ mw.hasta_id + "' ORDER BY tedavi_tarih DESC";
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;";
I made SQL table editor for add info in some columns. But one column is set to "DateTime" in and application can't write it . Here is the code:
private void button2_Click(object sender, EventArgs e)
{
try
{
string connectionString = #"Data Source=" + textBox4.Text + ";" + "Initial Catalog=" + textBox1.Text + ";" + "User ID=" + textBox2.Text + ";" + "Password=" + textBox3.Text;
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO user_ban (char_id, status, ban_date, ban_hour, ban_end) VALUES (#char_id, #status, DateTime #ban_date, #ban_hour, #ban_end)";
command.Parameters.AddWithValue("#char_id", "1");
command.Parameters.AddWithValue("#status", "1");
command.Parameters.AddWithValue("#ban_date", "1");
command.Parameters.AddWithValue("#ban_hour", "1");
command.Parameters.AddWithValue("#ban_end", "1");
connection.Open();
command.ExecuteNonQuery();
MessageBox.Show("Char Banned");
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
Column 'ban_date' is set to DateTime.
Thank you!
"1" is not a date. Try passing a date to it
command.Parameters.AddWithValue("#ban_date", DateTime.Today);
And remove the DateTime from the command string
command.CommandText = "INSERT INTO user_ban
(char_id, status, ban_date, ban_hour, ban_end)
VALUES
(#char_id, #status, #ban_date, #ban_hour, #ban_end)";
If ban_date column is DateTime, why you want to insert 1 to it? Does not make sense. 1 is not a valid DateTime at all. Change it to a valid DateTime value.
Second, you should not use value type in your VALUES part. Change it from
command.CommandText = "INSERT INTO user_ban (char_id, status, ban_date, ban_hour, ban_end)
VALUES (#char_id, #status, DateTime #ban_date, #ban_hour, #ban_end)";
^^^^^^^^^//delete this
to
command.CommandText = "INSERT INTO user_ban (char_id, status, ban_date, ban_hour, ban_end)
VALUES (#char_id, #status, #ban_date, #ban_hour, #ban_end)";
I am Working in ASP.NET and SqlServer.
I have two textboxes with calender extender in my application where user will select two dates.I want to get data between those two dates from sqlserver where my datatype for that particular field is DateTime. please tell me how to proceed with this ...I wrote a query but thats not working..
my query:
SqlCommand cmd = new SqlCommand("select top 1 OrderNumber from tblOrderMaster where OrderedDate>='" + txtfromcal.Text + "' and OrderedDate<='" + txttocal.Text + "' ", conn);
things to do
parameterized the query to prevent from sql injection
use using statement to properly dispose the object
use try-catch block to handle excpetion
eg,
string query = #"select top 1 OrderNumber
from tblOrderMaster
where OrderedDate BETWEEN #startDate AND #endDate";
using(SqlConnection conn = new SqlConnection("connectionString here"))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#startDate", txtfromcal.Text);
cmd.Parameters.AddWithValue("#endDate", txttocal.Text);
try
{
conn.Open();
// other codes
// to fetch the record
}
catch(SqlException e)
{
// do something with
// e.ToString()
}
}
}
SOURCES
AddWithValue Method
Add (recommended method to be used)
use this code:
Sqlcommand cmd=new sql command ("Select data from tablename
where date>=startdate
and date<=enddate",connection)
Try this
SELECT * FROM YourTableName WHERE sqlDateColumnName BETWEEN '" + textbox1.Text + "' AND '" + textbox2.Text + "'
I have a sentence follow:
string strSQL = "update pl_poli set ag_vouch = ' ',ag_vdate = #, ag_vmode = null where
pl_no = '" + textBox5.Text + "' and pl_endtno ='" + textBox6.Text + "'";
I can't update because error "data type mismath". i have fill ag_vdate is type date
I want to Update it -> null
Please can you help me. Thank you so much.
In your case you cannot pass " # " at datetime column because sql server consider this as varchar value and not able to convert this in datetime so...
Try to do as below
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO table1 (column1, column2) VALUES (#param1, #param2)";
command.Parameters.Add("#param1", SqlDbType.DateTime).Value =
DateTime.TryParse(txtDate.Text, out d) ?
(object)d :
DBNull.Value // inserting NULL
...
connection.Open();
command.ExecuteNonQuery();
}