The conversion of a char data type to a datetime d

2019-03-04 22:11发布

问题:

I have a WPF application. date is my table and its two columns are employeename (varchar(10)) and date (datetime)

My code is:

Sqlconncetion con = new Sqlconnection("my database connection ");    
SqlCommand cmd = new SqlCommand("insert into date values('"+textBox1.Text+"','"+datePicker1.Text+"')", con);    
con.Open();               
int n = cmd.ExecuteNonQuery();                
if (n > 0)
{
    MessageBox.Show("insert");
}

Actually my WPF datepicker formats inputs as "dd/mm/yyyy" and SQL Server table accept date format mm/dd/yyyy. How can I change my SQL Server datetime datatype date format? please give solution by code in c#..

My task is to display all name and birth date. My condition is basic but at time of date selection and button enter, I get exception. My code is

SqlConnection con = new SqlConnection("my connection ");

SqlDataAdapter da = new SqlDataAdapter("select name,date from date where date between'"+ Convert.ToDateTime( datePicker2.SelectedDate)+"' and  '"+ Convert.ToDateTime( datePicker3.SelectedDate)+"'",con);

DataSet ds = new DataSet();

da.Fill(ds, "entry");

da.Dispose();

dataGrid1.DataContext = ds.Tables["entry"].DefaultView; 

plz help me solve code error and write correct code . this is a WPF application.

回答1:

Use SqlParameters to pass your values to database. It gives you type safety, performance, and prevents SQL injection. Also use using statement to guarantee database connection will be closed:

var cmdText = "INSERT INTO date VALUES(@name, @date)";

using(var con = new SqlConnection(conString))
using(var cmd = new SqlCommand(cmdText, con)) {
     cmd.Parameters.Add("@name", textBox1.Text);
     cmd.Parameters.Add("@date", datePicker1.SelectedDate);
     con.Open();
     int n = cmd.ExecuteNonQuery();
     //...
}