Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

c# - Inserting datetime type char from form into database

I'm trying to insert a datetime value into my database table, but I'm ancountring a problem. Each time I try to do this, this message pops up:

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. The statement has been terminated.

This is my code:

public static void  DoQuery(string fileName, string sql)
{

    SqlConnection conn = ConnectToDb(fileName);
    conn.Open();
    SqlCommand com = new SqlCommand(sql, conn);
    com.ExecuteNonQuery();
    com.Dispose();
    conn.Close();
  
}
    private void button1_Click(object sender, EventArgs e)
    {
        SqlConnection cn = new SqlConnection();
        cn.ConnectionString = @"Data Source=.SQLEXPRESS;AttachDbFilename='c:users******visual studio 2010Projects******Database.mdf';Integrated Security=True;User Instance=True";
        cn.Open();
        string[] dateArr = dateBox.Text.Split('/');
        int[] dateInt = new int[3];
        for (int i = 0; i < 3; i++)
        {
            dateInt[i] = Int16.Parse(dateArr[i]);
            MessageBox.Show(dateInt[i]+"");
        }
        DateTime date = new DateTime(dateInt[2],dateInt[1],dateInt[0]);
        
        string sql = "INSERT INTO existProducts(name,date,price,amount) VALUES ('" + nameBox.Text + "','" + date + "','" + priceBox.Text + "','" + amountBox.Text + "')";

        MyAdoHelper.DoQuery("Database.mdf", sql);
        MessageBox.Show("Success!");
       
        cn.Close();
    }

Note 1: I had an exeption handling but I removed it because I always had to handle this exception and the program didn't run well.

Note 2: I censored the connection string, but there is a connection and it works fine.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use Parameters and most probabbly your problem wil be solved, and (another important thing) you will be secure yourself from the injection atack too.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...