具体布局:label,textBox(文本框),button(事件按钮),radioButton(单选按钮),dateTimePicker(时间控件),datagridView(显示数据)
全局变量:
//2.创建连接
//连接字符串
string connstr = "Data Source=数据库名.;Initial Catalog=School;Persist Security Info=True;User ID=数据库登录用户名;Password=数据库登录密码";
SqlConnection conn = new SqlConnection(connstr);
conn.Open();//打开连接
增:
//1.拼接sql语句
string name = this.txt_Name.Text;//获取姓名
string sex = this.rdoMen.Checked ? "男" : "女";//获取性别
string gotime = this.dateGoTime.Value.ToString("yyyy-MM-dd");//获取入学时间 yyyy表示年份,MM表示月,dd表示日
string age = this.textBox2.Text;//获取年龄
string sql = @"insert into Student(name,sex,gotime,age) values('" + name + "','" + sex + "','" + gotime + "','" + age + "')";
//3执行sql,创建sqlCommand
SqlCommand sc = new SqlCommand(sql, conn);
int count = sc.ExecuteNonQuery();//返回受影响的行数
if (count > 0)
{
this.Form3_Load(sender,e); //调用load事件刷新页面,可以改成MessageBox.Show("成功")
}
else
{
Console.WriteLine("新增失败!");
}
//关闭连接
conn.Close();
删
//获取选中行id
int id = Convert.ToInt32(this.dataGridView1.SelectedRows[0].Cells["id"].Value);
//根据id删除的sql语句
string sql = "delete from Student where id='"+id+"'";
bool isOk = DBHelper.ExcuteBySql(sql);
if(isOk){
MessBoxage.Show("删除成功");
}else{
MessBoxage.Show("删除失败");
}
改
//获取选中行id
int id = Convert.ToInt32(this.dataGridView1.SelectedRows[0].Cells["id"].Value);
//修改
string name = this.txt_Name.Text;//获取姓名
string sex = this.rdoMen.Checked ? "男" : "女";//获取性别
string gotime = this.dateGoTime.Value.ToString("yyyy-MM-dd");//获取入学时间 yyyy表示年份,MM表示月,dd表示日
string age = this.textBox2.Text;//获取年龄
string sql = "update Student set name='" + name + "',sex='" + sex + "',gotime='" + gotime + "',age='" + age + "' where id='" + id + "'";
bool isOk = DBHelper.ExcuteBySql(sql);
this.Form3_Load(sender, e);//调用load事件进行刷新
查
//拼接查询sql语句
string sql = "select * from Student where name like '%" + this.textBox1.Text + "%'";
string sex = this.comboBox1.Text.ToString().Trim();
if (sex == "不限" || sex == "")
{
}
else
{
sql = sql + " and sex='" + sex + "'";
}
//连接字符串
SqlConnection conn = new SqlConnection(connstr);
//执行sql语句
SqlDataAdapter sda = new SqlDataAdapter(sql, conn);
DataTable dt = new DataTable();
sda.Fill(dt);
//绑定datagridview的数据源,展示数据
this.dataGridView1.DataSource = dt;
conn.Close();
load事件:
绑定查询事件
新手搞代码第一天~~~