[C#] 从数据库读取数据并输出

 

连接数据库,并从数据库中读取数据后并输出!

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace Login
{
    class Program
    {
        static void Main(string[] args)
        {
            //新建一个数据库连接
            using(SqlConnection conn = new SqlConnection(GetConnectString()))
            {
                conn.Open();//打开数据库
                //Console.WriteLine("数据库打开成功!");
                //创建数据库命令
                SqlCommand cmd = conn.CreateCommand();
                //创建查询语句
                cmd.CommandText = "SELECT * FROM userinfo";
                //从数据库中读取数据流存入reader中
                SqlDataReader reader = cmd.ExecuteReader();               
                
                //从reader中读取下一行数据,如果没有数据,reader.Read()返回flase
                while (reader.Read())
                {
                    //reader.GetOrdinal("id")是得到ID所在列的index,
                    //reader.GetInt32(int n)这是将第n列的数据以Int32的格式返回
                    //reader.GetString(int n)这是将第n列的数据以string 格式返回
                    int id = reader.GetInt32(reader.GetOrdinal("id"));
                    string name = reader.GetString(reader.GetOrdinal("name"));
                    string pwd = reader.GetString(reader.GetOrdinal("password"));
                    int age = reader.GetInt32(reader.GetOrdinal("age"));
                    string sex = reader.GetString(reader.GetOrdinal("sex"));
                    string phone = reader.GetString(reader.GetOrdinal("phone"));
                    string address = reader.GetString(reader.GetOrdinal("Address"));

                    //格式输出数据
                    Console.Write("ID:{0},Name:{1},PWD:{2},Age:{3},Sex:{4},Phone{5},Address:{6}\n", id, name, pwd, age, sex, phone, address);
                }
            }
            Console.ReadKey();
        }
        //得到一个数据库连接字符串
        static string GetConnectString()
        {
            return "Data Source=(local);Initial Catalog=db1;Integrated Security=SSPI;";
        }
    }
}


 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值