zoukankan      html  css  js  c++  java
  • 从数据库中读出数据并输出

    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5. using System.Data.SqlClient;  
    6.   
    7. namespace Login  
    8. {  
    9.     class Program  
    10.     {  
    11.         static void Main(string[] args)  
    12.         {  
    13.             //新建一个数据库连接  
    14.             using(SqlConnection conn = new SqlConnection(GetConnectString()))  
    15.             {  
    16.                 conn.Open();//打开数据库  
    17.                 //Console.WriteLine("数据库打开成功!");  
    18.                 //创建数据库命令  
    19.                 SqlCommand cmd = conn.CreateCommand();  
    20.                 //创建查询语句  
    21.                 cmd.CommandText = "SELECT * FROM userinfo";  
    22.                 //从数据库中读取数据流存入reader中  
    23.                 SqlDataReader reader = cmd.ExecuteReader();                 
    24.                   
    25.                 //从reader中读取下一行数据,如果没有数据,reader.Read()返回flase  
    26.                 while (reader.Read())  
    27.                 {  
    28.                     //reader.GetOrdinal("id")是得到ID所在列的index,  
    29.                     //reader.GetInt32(int n)这是将第n列的数据以Int32的格式返回  
    30.                     //reader.GetString(int n)这是将第n列的数据以string 格式返回  
    31.                     int id = reader.GetInt32(reader.GetOrdinal("id"));  
    32.                     string name = reader.GetString(reader.GetOrdinal("name"));  
    33.                     string pwd = reader.GetString(reader.GetOrdinal("password"));  
    34.                     int age = reader.GetInt32(reader.GetOrdinal("age"));  
    35.                     string sex = reader.GetString(reader.GetOrdinal("sex"));  
    36.                     string phone = reader.GetString(reader.GetOrdinal("phone"));  
    37.                     string address = reader.GetString(reader.GetOrdinal("Address"));  
    38.   
    39.                     //格式输出数据  
    40.                     Console.Write("ID:{0},Name:{1},PWD:{2},Age:{3},Sex:{4},Phone{5},Address:{6} ", id, name, pwd, age, sex, phone, address);  
    41.                 }  
    42.             }  
    43.             Console.ReadKey();  
    44.         }  
    45.         //得到一个数据库连接字符串  
    46.         static string GetConnectString()  
    47.         {  
    48.             return "Data Source=(local);Initial Catalog=db1;Integrated Security=SSPI;";  
    49.         }  
    50.     }  
    51. }  
  • 相关阅读:
    为蓝桥杯准备
    Java里子类调用父类构造方法问题
    boost库的Singleton的实现以及static成员的初始化问题
    VS2005调试小记
    <转载>程序员每天该做的事
    vs2005, 2008 使用了未初始化的msg变量
    转载 vs2005 快捷键大全
    VS2005右键点击转到定义后出现“未定义符号”的提示及其解决
    软件工程配置规范(VC2005) 第二版(转载)
    匆忙赶路的时候别忘了适时停下来回头看看
  • 原文地址:https://www.cnblogs.com/yanyao/p/5616062.html
Copyright © 2011-2022 走看看