Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...