.Net C# 连接数据库

来源:互联网 发布:电子数据库有哪些 编辑:程序博客网 时间:2024/05/16 12:05


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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main_(string[] args) 
        { 
            String sql = "select * from emp";   //sql查询语句 
            string connString = @"Data Source=.\SQLEXPRESS;Initial Catalog=tt;User ID=sa;Password=tiger"; //Sql数据库联接字符串 
           
            SqlConnection conn = new SqlConnection(connString);  //数据库联接对象 
            
            SqlCommand comm = new SqlCommand(sql, conn);     //命令对象 
           
            conn.Open(); 
         
            SqlDataReader reader = comm.ExecuteReader(CommandBehavior.CloseConnection);    //SqlDataReader对象,单步执行,速度快 

            
            while (reader.Read()) 
            { 
                Console.WriteLine("id-----" + reader.GetInt32(0)); 
                Console.WriteLine("name--------" + reader.GetString(2));
                Console.WriteLine("age-------" + reader.GetInt32(1));
 
            }

            Console.ReadKey(); 
            reader.Close();

        }

}

}


原文链接  http://www.cnblogs.com/Tim-Seven/archive/2011/01/18/1952430.html