Go to my github

C#:System.Data.Common命名空间(数据库抽象工厂的使用)

代码
///在使用本例之前要先手动引用system.configration组件,然后建立config文件,config文件名为当前程序文件名的后面加.config比如:a.exe.config
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;

namespace ConsoleApplication313
{
    
class Program
    {
        
static void Main(string[] args)
        {
            ConnectionStringSettings cfg 
= ConfigurationManager.ConnectionStrings["My DB"];
            DbProviderFactory factory 
= DbProviderFactories.GetFactory(cfg.ProviderName);
            DbConnection cnx 
= factory.CreateConnection();
            DbCommand cmd 
= factory.CreateCommand();
            cnx.ConnectionString 
= cfg.ConnectionString;
            cmd.Connection 
= cnx;
            cnx.Open();
            cmd.CommandText 
= string.Format("select * from student");
            DbDataReader dbdatareader
=
            cmd.ExecuteReader();
            
while (dbdatareader.Read())
            {
                Console.Write(
string.Format("{0} {1} {2} {3} {4} {5}",dbdatareader[0],dbdatareader[1],
                    dbdatareader[
2],dbdatareader[3],dbdatareader[4],dbdatareader[5]));
                Console.WriteLine();
            }
            System.Console.ReadLine();
        }
    }
}




 

下面是XML文件的内容:

代码
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
   
<add name="My DB" providerName="System.Data.SqlClient" connectionString="server=.;uid=sa;pwd=sqlserver;database=master"/>
</connectionStrings>
</configuration>

 

 

 

posted @ 2010-03-04 14:45 罗敏贵 阅读(...) 评论(...) 编辑 收藏