環境:
1、SQLite數據庫新建數據表,設置相應的字段。(其他數據庫形式都相似,using相應數據庫的包即可)
2、頁面有兩個textBox:textBox1、textBox2,
3、一個保存按鈕:點擊保存按鈕就會保存到數據庫
實現:
將從頁面獲取的數據,傳入到數據庫
一、新建一個類DBDao.cs,封裝的連接數據庫的方法ExecuteSql()
public static int ExecuteSql(string sql, params SQLiteParameter[] parameters) { using (SQLiteConnection con = new SQLiteConnection(Constants.DATA_SOURCE)) { con.Open(); using (SQLiteCommand cmd = new SQLiteCommand()) { cmd.Connection = con; cmd.CommandText = sql; cmd.Parameters.AddRange(parameters); return cmd.ExecuteNonQuery(); } } }
二、在頁面的兩個文本框輸入數據,點擊保存按鈕,
private void button1_Click(object sender, EventArgs e) { string id= textBox1.Text; string name= textBox2.Text; string sql = @"insert into test(id,name) values (@id,@name)"; DBDao.ExecuteSql(sql, new SQLiteParameter("@id", id), new SQLiteParameter("@name", name)); }
OK
三、其他
1、C#生成唯一的ID保存到數據庫
直接用.NET Framework 提供的 Guid() 函數:
Guid.NewGuid()是指生成唯一碼的規則
System.Guid.NewGuid().ToString()全球唯一標識符 (GUID) 是一個字母數字標識符
System.Guid.NewGuid().ToString(format):生成的ID值的格式:
說明符 返回值的格式
N 32 位:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
D 由連字符分隔的 32 位數字:
xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
B 括在大括號中、由連字符分隔的 32 位數字:
{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
P 括在圓括號中、由連字符分隔的 32 位數字:
(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
Guid guid = Guid.NewGuid(); string id = guid.ToString("N");
保存到數據庫中后,就是一串32位的字符串
2、獲取dateTimePicker1日期:
DateTime date = dateTimePicker1.Value; string yxq = date.ToString("yyyy-MM-dd");
日期格式化為:“年-月-日”