1、增加:
//增加
private void button2_Click(object sender, EventArgs e)
{
string uname=textBox2.Text;
string upass=textBox1.Text;
SqlConnection conn = new SqlConnection("server=.;database=data1220;user=sa;pwd=sa");
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "insert into table1 values(‘"+uname+"‘, ‘"+upass+"‘)";
int count=cmd.ExecuteNonQuery();
if (count > 0)
{
MessageBox.Show("增加成功");
}
else
{
MessageBox.Show("增加失败");
}
conn.Close();
}
执行结果:
2、删除
//删除
private void button4_Click(object sender, EventArgs e)
{
string code = textBox3.Text;
SqlConnection conn = new SqlConnection("server=.;database=data1220;user=sa;pwd=sa");
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "delete from table1 where code="+code;
cmd.ExecuteNonQuery();
conn.Close();
}
3、修改
//修改
private void button3_Click(object sender, EventArgs e)
{
string uname = textBox2.Text;
string upass = textBox1.Text;
string code = textBox3.Text;
SqlConnection conn = new SqlConnection("server=.;database=data1220;user=sa;pwd=sa");
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "update table1 set uname=‘"+uname+"‘,upass=‘"+upass+"‘where code="+code;
int count=cmd.ExecuteNonQuery();
if (count > 0)
{
MessageBox.Show("修改成功");
}
else
{
MessageBox.Show("修改失败");
}
conn.Close();
}
4、查询
//查询
private void button1_Click(object sender, EventArgs e)
{
string uname=textBox2.Text;
string upass=textBox1.Text;
//连接数据库
SqlConnection conn = new SqlConnection("server=.;database=data1220;user=sa;pwd=sa");
conn.Open();
//写执行语句
SqlCommand cmd = conn.CreateCommand(); //通过conn创建SqlCommand对象
cmd.CommandText = "select *from table1 where uname=‘"+uname+"‘ and upass=‘"+upass+"‘ ";
SqlDataReader dr = cmd.ExecuteReader(); //执行查询,返回SqlDataReader对象
if (dr.Read())
{
MessageBox.Show("登陆成功");
}
else
{
MessageBox.Show("登陆失败");
}
conn.Close();
}