Oct 12, 2015

C# using mysql(database)



This post is using database(My sql).





Above image is testing image.


Displaying datetimepicker's date data.


Default date is today.

1
dateTimePicker1.Value = DateTime.Now;

C# possible to using sync way or async way.

I using async way.

This is database.

schema is test, table is answertest.

There are 4 columns.

id is primary key.

No is number, Record is counter or timer, Date is recording date.

1
2
3
4
5
6
7
8
String strCon = "Server=localhost;Database=test;Uid=test;Pwd=;";
DataSet ds = new DataSet();
string sql = "SELECT * FROM answertest where date like '"+date+"%'";
using(MySqlConnection conn=new MySqlConnection(strCon))
{
      MySqlDataAdapter adpt = new MySqlDataAdapter(sql, conn);
      adpt.Fill(ds, "answertest");
}


I use 3 objects MySqlConnection, MySqlDataAdapter and DataSet

Line 1 : Basic information for connect to mysql.

Line 3 : I use 'like' because db saved date and time, but i use date for query. 

Line 7 : save query data to dataset.

I use foreach.

1
2
3
4
5
6
7
 foreach(DataRow r in ds.Tables[0].Rows)
 {               
    ListViewItem lv = new ListViewItem(r["no"].ToString());
    lv.SubItems.Add(r["record"].ToString());
    lv.SubItems.Add(r["date"].ToString());
    listView2.Items.Add(lv);
 }

Press button '기록'(record), insert db.

1
2
3
4
5
6
7
using (MySqlConnection conn = new MySqlConnection(strCon))
{
    conn.Open();
    MySqlCommand cmd = new MySqlCommand("INSERT INTO answertest (no,record,date) VALUES 
("+recordCnt+",'"+timerText.Text+"','"+dateTimeText.Text.ToString()+"')", conn);
    cmd.ExecuteNonQuery();
}

No comments:

Post a Comment