本文最后更新于 976 天前,其中的信息可能已经有所发展或是发生改变。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OracleClient;
namespace OracleTest //命名空間
{
public class Program //類名
{
static void ReadFromOracleTest() //方法名——連接數據庫,并抓取資料
{
/*組合連接字符串
參考oracle目錄下的tnsnames.ora文件里的信息
*/
string conn = string.Concat(
@”Data Source=”,
@” (DESCRIPTION=”,
@” (ADDRESS_LIST=”,
@” (ADDRESS=”,
@” (PROTOCOL=TCP)”,
@” (HOST=172.17.0.96)”,
@” (PORT=1521)”,
@” )”,
@” )”,
@” (CONNECT_DATA=”,
@” (SERVICE_NAME=TOPDB)”,
@” )”,
@” );”,
@”Persist Security Info=True;”,
@”User Id=avydg;”, //登入用戶
@”Password=avydg” //用戶密碼
);
OracleConnection oc = new OracleConnection(conn); //創建數據庫連接對象,傳入連接字串
try
{
oc.Open(); //打開數據庫連接
OracleCommand cmd = oc.CreateCommand(); //創建對象
//cmd.CommandText = “select sysdate from dual”;
Console.Write(“請輸入查詢人員名稱:”);
string length = Convert.ToString(Console.ReadLine()); //接受輸入的參數
cmd.CommandText = “select zx01,zx03 from zx_file where zx02 = ‘”; //查詢語句
cmd.CommandText = cmd.CommandText+length+”‘”; //補充sql語句
//Console.Write(cmd.CommandText);
OracleDataReader oder = cmd.ExecuteReader(); //創建讀取數據的對象
while (oder.Read()) //開始讀取數據
{
OracleString oraclestring1 = oder.GetOracleString(0); //將數據轉換成OracleString類型,這裡獲取的在zx01字段
OracleString oraclestring2 = oder.GetOracleString(1);
Console.WriteLine(“員工的ERP賬號為 : ” + oraclestring1.ToString()); //顯示結果
Console.WriteLine(“員工的部門代碼為: ” + oraclestring2.ToString());
//Console.WriteLine(oder.GetOracleDateTime(0).ToString());
}
}
catch (Exception ex) //捕捉異常的執行塊
{
Console.WriteLine(ex.Message);
}
finally
{
oc.Close(); //關閉連接
}
}
static void Main(String[] args)
{
ReadFromOracleTest(); //調用方法
Console.ReadLine(); //等待
}
}
}