zoukankan      html  css  js  c++  java
  • C# winform窗体设计-通过条件查询数据

         在winform 数据库设计中,有时候需要通过条件查询对应的数据,并且将数据显示在文本框(or 富文本框)中,下面,小编将讲述通过一个条件:

    首先,我们需要对数据库建立连接,并且执行数据库命令,在此之前,我们先创建一个winform窗体,窗体设计大概如下所示:

       在创建窗体后,我们应该进行书写代码阶段:

     1             string s = "server=SAM_PC;database=MInformationDB;Integrated Security=true";
     2             SqlConnection con = new SqlConnection(s);
     3             con.Open();
     4             string sql =string.Format( "select * from Student where Grade='{0}'",textBox1.Text);
     5             SqlCommand command = new SqlCommand(sql, con);
     6 
     7             SqlDataReader reader = command.ExecuteReader();
     8             while (reader.Read())
     9             {
    10                 string id = (String)reader["Id"];
    11                 string name = (String)reader["Name"];
    12                 int age = (int)reader["Age"];
    13                 string gender = (string)reader["Gender"];
    14                 string major = (string)reader["Major"];
    15                 textBox2.Text += String.Format("{0}	{1}	{2}	{3}	{4}
    ", id, name, age, gender, major);
    16             }

    ---->

    SKILLS:

    -----------当查询结果可能返回多行多列时,需要使用DataReader读取返回的数据

    DataReader的功能是每次一行从读取数据
    主要方法:
    -----------Read方法:从数据库读取一行数据,返回bool,为true说明读取到了数据,false说明已经全部读取完成,无数据可读了。
    -----------[“列名”]:取得当前行某字段的值,返回object类型,通常要类型转换
    -----------Close:使用完毕后关闭,释放资源
     
     
    读取数据的步骤:
    -----------(0)创建连接、创建命令、打开连接同前
    -----------(1)SqlCommand.ExecuteReader返回一个SqlDataReader对象
    -----------(2)SqlDataReader.Read方法读取一行数据
    -----------(3)SqlDataReader[“列名”]读取当前行的某一列,为object类型,需要类型转换
    -----------(4)重复执行(3)步骤读取其他字段
    -----------(5)转到(2)读取下一行数据
  • 相关阅读:
    source is null for getProperty(null, "cpmodel")异常结局
    insert时报Cannot add or update a child row: a foreign key constraint fails (`yanchangzichan`.`productstatusrecord`, CONSTRAINT `p_cu` FOREIGN KEY (`cid`) REFERENCES `customer` (`cid`))错误
    Python流程控制
    Python运算符
    Python字符串格式化输出
    Python数据强制类型转换
    Python数据类型
    Python input函数使用
    Python print函数使用
    Python变量
  • 原文地址:https://www.cnblogs.com/boy1025/p/4087701.html
Copyright © 2011-2022 走看看