链接数据库
static string connstr = "Data Source=.;Initial Catalog=数据库名;Integrated Security=True";
SqlConnection conn = new SqlConnection(connstr);
添加数据
private void btn_add_Click(object sender, EventArgs e)
{
string name = this.txt_Name.Text;
string pass = this.txt_pass.Text;
int sex = rdb_man.Checked ? 0 : 1;
string hobby = string.Empty;
foreach (CheckBox item in gb_hobby.Controls)
{
if (item.Checked)
{
hobby += item.Text + " ";
}
}
string city = cb_city.Text;
string ad = this.txt_advice.Text;
//定义sql语句
string sql = $"insert into UserInfo values('{ name}','{ pass }',{ sex },'{ hobby }','{city }','{ ad }')";
//创建command对象
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
//打开数据库
conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("添加成功", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}