cdc

导航

ADO.NET下各种DB的连接方法

Posted on 2006-04-21 11:41  Chris Chen  阅读(318)  评论(0)    收藏  举报

1、连接Excel
    

      //后面的 Excel与8.0之间有一个空格
        string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("./test.xls") + ";Extended Properties=Excel 8.0;";
       
        OleDbConnection conn = new OleDbConnection(connectionString);
        conn.Open();
       
        OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", conn);   //[Shee1$]中的Sheet1是分页的名称
        OleDbDataAdapter myAdapter = new OleDbDataAdapter(cmd);
        myAdapter.SelectCommand = cmd;
        DataSet myDataSet = new DataSet();
        myAdapter.Fill(myDataSet,"test");

        grExcel.Caption = "Excel表格内容";

        //"test"是Excel文件名

        //grExcel是一个 Gridview组件
        grExcel.DataSource = myDataSet.Tables["test"].DefaultView;
        grExcel.DataBind();
        conn.Close();

 

2、连接Access

    

     string connectString = "Microsoft.Jet.OLEDB.4.0;Data Source=C:\My.mdb;User ID=;Password=;";

    //Use a string variable to hold the ConnectionString.
     string connectString = "Provider=Microsoft.Jet.OLEDB.4.0;"Data Source=C:\My.mdb;User ID=;Password=";
 
    //Create an OleDbConnection object, 
    //and then pass in the ConnectionString to the constructor.
    OleDbConnection cn = new OleDbConnection(connectString);
 
    //Open the connection.
    cn.Open();
 
    //Use a variable to hold the SQL statement.
     string selectString = "SELECT CustomerID, ContactName, Phone FROM Customers";

     //Create an OleDbCommand object.
     //Notice that this line passes in the SQL statement and the OleDbConnection object


     OleDbCommand cmd = new OleDbCommand(selectString,cn);
     //Send the CommandText to the connection, and then build an OleDbDataReader.
     //Note: The OleDbDataReader is forward-only.
     OleDbDataReader reader = cmd.ExecuteReader();

 

3、SQL SERVER链接

 

     You next create a connection string that points to a SQL Server database. A connection string has a set of semi-colon-separated attributes. Each .Net Data Provider connection string looks different, depending on the type of .NET Data Provider you need to use and which attributes are set for each different type of database system. For example, the connection string below is an example of what you use to connect to a local SQL Server.


    Data Source=(local);Initial Catalog=Northwind;User ID=sa;Password=;