Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello.
I want to chose date-time from DateTimePicker and add this value to MySQL.
In my data table, I create column "date_time" with datetype type.
And then I set "CustomFormat" of DateTimePicker is "dd-MM-yyyy".
I write code to insert datetime value to MySQL, but value in my data table is 0000-00-00 00:00:00.
Orther column is good.
Please help me this problem. Thank you.
Here is my code
C#
//connect_data();
           byte[] imageBt = null;
           if (txt_path.Text != "")
           {
               FileStream fstream = new FileStream(this.txt_path.Text, FileMode.Open, FileAccess.Read);
               BinaryReader br = new BinaryReader(fstream);
               imageBt = br.ReadBytes((int)fstream.Length);
           }
           else
           {
               imageBt = null;
           }

           String myConnection = "Server=localhost;Database=sctv_data;Port=3306;User ID=root;Password=;Charset=utf8";
           MySqlConnection conDatabase = new MySqlConnection(myConnection);
           string Query = "INSERT into nhap (STT,Ngay_nhap,Ten_thiet_bi,Nha_san_xuat,Don_vi,So_luong,Nhan_tu,Chip_ID,MAC_address,SN,Ghi_chu,Hinh) values ('" + txt_STT.Text + "','" +this.dateTimePicker1.Text+ "','" + txt_ten_tb.Text + "','" + txt_nha_sx.Text + "','" + txt_don_vi.Text + "','" + txt_so_luong.Text + "','" + txt_nhan_tu.Text + "','" + txt_chip_ID.Text + "','" + txt_mac.Text + "','" + txt_sn.Text + "','" + txt_note.Text + "',@hinh);";
           MySqlCommand cmdDataBase = new MySqlCommand(Query, conDatabase);
           MySqlDataReader myReader;
           try
           {
               conDatabase.Open();
               cmdDataBase.Parameters.Add(new MySqlParameter("@hinh", imageBt));
               myReader = cmdDataBase.ExecuteReader();
               MessageBox.Show("SAVE");
               while (myReader.Read())
               {
               }
           }
           catch (Exception ex)
           {
               MessageBox.Show(ex.Message);
           }
Posted

1 solution

The first thing you need to do is not to concatenate literals into SQL statement. Doing so leaves you open to SQL injections and makes handling values much harder. Instead use MySqlParameter[^].

After that make sure that the date column is included in the INSERT statement. At the moment there is no column named date_time mentioned so if that is the actual name of the column, it will have empty value after insert.
 
Share this answer
 
v3
Comments
Member 10390715 29-Jul-15 0:12am    
thank for your help
Wendelius 29-Jul-15 2:16am    
You're welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900