脚本入门(基础查询)

来源:互联网 发布:omron plc编程入门 编辑:程序博客网 时间:2024/06/13 23:22
 欢迎来到U3D社区:

什么是查询:

       查询产生一个虚拟表,看到的是表形式显示的结果,但结果并不真正存储,每次执行查询只是现从数据表中提取数据,并按照表的形式显示出来。

数据查询-基础语句:

查询全部的列和行:
        select*from 表名
查询部分行:
       select 列名 from  表名  where 条件 

去掉重复字段查询记录:

      select distinct  列名 from  表名
 
合并查询(合并两表中相同的字段)

      select *from 表名1 union select*from 表名2

使用 as 来命名列:

      select code as 学院编号, name as  学院姓名, address as  学院地址 from 表名

使用= 来命名列

      select ‘姓名’ = name from  表名

查询空行:

      select 列名 from  表名  where 条件 

使用常量列 

      select 姓名=name ,地址=address ,‘河北’ as 学校名称 from 表名

限制固定行数

      select top 5 name, address from  表名 where 条件 

排序

      select  列名 from  表名  where 查询条件表达式 ordear by asc或者 basc    asc 升序   basc 降序

按多列排序

      SELECT StudentID As 学员编号, Score As 成绩 FROM Score WHERE Score>60

连接数据库

      开始-->引入命名空间-->创建一个SqlConnection对象-->打开连接-->创建一个SqlCommand对象-->关闭连接-->关闭SqlDataReader对象--
--->获取SqlDataReader对象-->结束。

步骤:

引入
      using System.Data;
      using System.Data.SqlClient;

 public void Get
 {
           SqlConnection con = new SqlConnection("server=.;uid = ; pwd =;database =second;");

           SqlCommand cmd=new SqlCommand("select * from users",con);

           con.Open();

                SqlDataReader myreader=cmd.ExecuteReader();

           while (myreader.Read())

            {
                Console.WriteLine(myreader.GetValue(0) + "   " +  

                myreader.GetValue(1));   

            }
            myreader.Close();

            con.Close(); 
          }

查询功能

      public List<Users> select() {

            List<Users> list = new List<Users>();

            SqlConnection con = new SqlConnection("server=127.0.0.1;uid =    sa; pwd =wang;database =second");
                  
            SqlCommand cmd = new SqlCommand("select * from users", con);

            con.Open();

            SqlDataReader myreader = cmd.ExecuteReader();

            while (myreader.Read())

            {
                Users u = new Users();

                u.Id =(int) myreader.GetValue(0);

                u.Name =(string) myreader.GetValue(1);

                u.Password = (string)myreader.GetValue(2);

                list.Add(u);

           }

插入:

       public int insert(){
            SqlConnection con = new SqlConnection("server=127.0.0.1;uid = 
                                            sa; pwd =wang;database =second");
            string sql = "insert into users(name,password) values('王五','789')";
            SqlCommand comm = new SqlCommand(sql, con);
            con.Open();
            int count = comm.ExecuteNonQuery();
            return count;
        }

更多精彩在http://unity.gopedu.com/forum.php

0 0