数据库的基本操作
数据的插入:
public int insertStu(string name,string password,int age) { //传3个参数
SqlConnection con = DB.Connect(); / /与数据库建立连接
con.Open(); //打开数据库
string sql = "insert into users values('"+name+"','"+password+"',"+age+")"; //数据库插入语句
SqlCommand com = new SqlCommand(sql,con); //数据库命令语句
int i=com.ExecuteNonQuery(); //执行sql语句,返回整形int
return i;
}
数据的修改:
public int updateStu(string name, string password,int id)
{
SqlConnection con = DB.Connect();
con.Open();
string sql = "update stu set name='"+name+"',password='"+password+"' where id="+id+"";
SqlCommand com = new SqlCommand(sql, con);
int i = com.ExecuteNonQuery();
return i;
}
数据的删除:
public int deleteStu( int id)
{
SqlConnection con = DB.Connect();
con.Open();
string sql = "delete from stu where id="+id+"";
SqlCommand com = new SqlCommand(sql, con);
int i = com.ExecuteNonQuery();
return i;
}
数据的查询:
首先定义一个类stu,对其属性封装,然后在操作类中声明List<stu>=new List<stu>();
public List<Stu> selectAll()
//定义一个方法,返回的是对象
{
SqlConnection con = DB.Connect();
con.Open();
string sql = "select * from stu";
SqlCommand com = new SqlCommand(sql, con);
SqlDataReader reader = com.ExecuteReader(); //数据的读入
while(reader.Read()){
Stu s = new Stu();
s.Id = (int)reader.GetValue(0);
s.Name = (string)reader.GetValue(1);
s.Password = (string)reader.GetValue(2);
list.Add(s); //加入集合中
}
return list; //返回对象
}
数据的多表连接
1、内联接:通过内联接把两个表中相同字段组合成一个新的记录。
如:
Table A
TableB
aid adate bid bdate
1 a1 1 b1
2 a2 2 b2
3 a3 4 b4
两个表a,b相连接,要取出id相同的字段,查询语句为:
select * from a inner join b on a.aid = b.bid
结果是:
1 a1 b1
2 a2 b2
aid adate bid bdate
1 a1 1 b1
2 a2 2 b2
3 a3 4 b4
两个表a,b相连接,要取出id相同的字段,查询语句为:
select * from a inner join b on a.aid = b.bid
结果是:
1 a1 b1
2 a2 b2
更多精彩请点击 http://www.gopedu.com/