一、任务需求
在管理员主界面连接后台数据,完成新用户注册
二、前期准备(相关界面)
三、主要代码
private void bt_Ok_Click(object sender, EventArgs e)
{
String name = this.tb_Name.Text.Trim();
String age = this.tb_Age.Text.Trim();
String password = this.tb_Password.Text.Trim();
String xb = this.tb_XB.Text.Trim();
String type = this.cb_Type.Text.Trim();
// 连接字符串,注意与实际环境保持一致
String connStr = ConfigurationManager.ConnectionStrings["KQ"].ConnectionString;
SqlConnection sqlConn = new SqlConnection(connStr);
try
{
// 连接数据库
sqlConn.Open();
// 构造命令
String sqlStr = "insert into USERS (NAME,AGE,PASSWORD,TYPE,XB)values(@name,@age,@password,@type,@xb)";
SqlCommand cmd = new SqlCommand(sqlStr, sqlConn);
// SQL字符串参数赋值
cmd.Parameters.Add(new SqlParameter("@name", name));
cmd.Parameters.Add(new SqlParameter("@age", age));
cmd.Parameters.Add(new SqlParameter("@password", password));
cmd.Parameters.Add(new SqlParameter("@type", type));
cmd.Parameters.Add(new SqlParameter("@xb", xb));
// 将命令发送给数据库
int res = cmd.ExecuteNonQuery();
// 根据返回值判断是否插入成功
if (res != 0)
{
MessageBox.Show("商品信息录入成功");
}
else
{
MessageBox.Show("商品信息录入失败");
}
}
catch (Exception exp)
{
MessageBox.Show("访问数据库错误:" + exp.Message);
}
finally
{
sqlConn.Close();
}
}
四、成果展示