我们要做的就是将数据库和Windows窗体应用程序连接起来,在界面中输入一条记录,就可以插入到数据库中的某一个表中去。

在连接应用程序与数据库时,要先做这些准备:

①创建一个数据库;

②在数据库中添加几张表;

③学习SQL语言中的插入语句:InsertInto[表名](字段列表)Values(值列表);

④通过程序连接上数据库,创建命令、执行命令。

前面两步都很简单,我们可以轻松的完成。

InsertInto语句用于向表格中插入新的行.

语法:InsertInto表名称Values(值1,值2,....)

我们也可以指定所要插入数据的列:InsertInto表名称(列1,列2,...)Values(值1,值2,....

先看我们设计好的窗体:

133218949.png

在这个窗体中我们预先设置性别为男,以后操作时可以选择(应用RadioButton控件),时间可以自己在控件中选择(应用DateTimePicker控件),下面我们来看看应用程序是怎么写的:

/// <summary>
/// 添加按钮的Click时间
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSave_Click(object sender, EventArgs e)
{
//从窗体中取值
string name = txtName.Text;
string sex;
if (this.radMan.Checked == true)
{
sex = "1";
}
else
{
sex = "0";
}
DateTime birthday = this.dtpBirthday.Value;
string salary = this.txtSalary.Text;
//连接到数据库
string connString = @"server=.\sqlexpress;database=CardInfosDB;uid=sa;pwd=199298;";
SqlConnection connection=new SqlConnection(connString);
connection.Open();
//创建一个command对象
SqlCommand command = connection.CreateCommand();
//组织SQL语句
string sql = "Insert Into CardInfos(name, sex, birthday, salary)Values(@name,@sex,@birthday,@salary)";
//将要执行的SQL语句给Command对象
command.CommandText = sql;
//完善SQL语句
SqlParameter[] ps = new SqlParameter[] {
new SqlParameter("@name",name),
new SqlParameter("@sex",sex),
new SqlParameter("@birthday",birthday),
new SqlParameter("@salary",salary)
};
command.Parameters.AddRange(ps);
//执行SQL语句:将SQL语句发往数据库中去执行,只添加,不查询
int x=command.ExecuteNonQuery();
if (x!=0)
{
this.label5.Text = "添加成功咧。。。。。。";
}
connection.Close();
}
/// <summary>
/// 取消按钮的Click事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}

在连接数据库时我们用的是SqlConnection类,运用它创建一个连接,让数据库可以和程序通话,在执行插入的命令的时候,用的是SqlCommand类,这是命令类,可以应用它里面的ExecuteNonQuery()方法执行我们的插入语句,将记录添加到数据库中去。

现在我们就可以实现数据库和应用程序的连接了,并应用这种连接往数据库中添加我们想要的数据信息,简单明了。

P.S.在选择数据类型的时候,我们要尽可能少的选择字符串,像工资、编号、性别这些我们就可以选择其他的类型如:money、int、bit;

SQL语句对大小写不敏感。