数据的基本操作与数据库的多表连接

数据库的基本操作

数据的插入:

            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


更多精彩请点击 http://www.gopedu.com/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值