ADO.NET與Oracle(一):擷取多行記錄集,ado.netoracle

來源:互聯網
上載者:User

ADO.NET與Oracle(一):擷取多行記錄集,ado.netoracle

最近接觸ADO.NET和Oracle,將我平常遇到的一些問題和大家共用。


我覺得要想入門ADO.NET操作Oracle,最基本的要求就是要會通過ADO.NET更新Oracle中的資料。

該文簡單講些利用Command對象更新資料庫

所有內容基於VS2010和Oracle11g(32bit)


1、串連資料庫

串連資料庫依靠OracleConnection對象

OracleConnection con = new OracleConnection("data source=orcl;uid=system;pwd=********");

orcl是資料庫的名字,這是安裝oracle時系統預設的。

安裝好資料庫後,也可以通過Database Configuration Assistant工具來刪除或建立資料庫

uid是登入名稱,pwd是登陸口令


要想串連到資料庫,只需執行con.Open()方法

而要中斷連線時,只需執行con.Close()或con.Dispose()方法。


2、操作資料庫

串連好資料庫,就可以對資料庫進行操作了

從最簡單的操作做起,即從資料庫中返回所有記錄

現在在資料庫中建立一個product表

如下:

ID Name Price Count
001 Apple 6 3
002 Orange 5 4
003 Pear 4 2

上表記錄了蘋果和橙子的ID以及單價和數量。

其中ID、Name都是varchar類型的資料,而Price和Count都是Number類型的資料


現在嘗試讀取表中的所有資料,再將這些資料完全顯示的螢幕上。

代碼如下

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data;using System.Data.OracleClient;namespace DataReader{    class Program    {        static void Main(string[] args)        {                                    try            {                using (OracleConnection con = new OracleConnection("data source=orcl;uid=system;pwd=wu92890910xu"))                {                    using (OracleCommand cmd = new OracleCommand("select * from product", con))                    {                        con.Open();                        OracleDataReader dataReader = cmd.ExecuteReader();                        if (dataReader.HasRows)                            Console.WriteLine("讀取到資料...");                        else                            Console.WriteLine("未讀取到資料...");                        while (dataReader.Read())                        {                            Console.WriteLine(dataReader.GetString(1) + ": " + dataReader.GetDouble(2) * dataReader.GetDouble(3));                        }                    }                                                       }                            }            catch (Exception ex)            {                Console.WriteLine(ex.Message);                        }                                                Console.ReadKey();        }    }}

你可以嘗試把select * from product  改成select id,name from product之類的語句


附:如果要使用ADO.NET操作Oracle,必須包括命名空間

using System.Data.OracleClient;

該命名空間是由Oracle公司提供的,NET本身不提供。

如果你需要那個.dll檔案,可以e-mail:cf520wuxu@outlook.com


相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.