關於用c#怎樣串連oracle的問題
來源:互聯網
上載者:User
嘗試連上Oracle,並用OracleCommand命令讀取資料庫中的記錄,顯示在控制台上: 1using System;
2using System.Data;
3using System.Data.OracleClient;
4
5public class MainClass
6{
7 static void Main()
8 {
9 OracleConnection conn = new OracleConnection();
10 conn.StateChange += new StateChangeEventHandler(OnStateChanged);
11 conn.ConnectionString = "Data Source = chenchong; User Id = system; Password = ;";
12 try
13 {
14 conn.Open();
15 Console.WriteLine("開啟資料庫連接成功。");
16 OracleCommand command = new OracleCommand();
17// command.CommandText = "";
18 command.CommandText = "select nsrmc from scott.nsr where nsrmc like :pNsrmc order by nsrmc";
19 command.Connection = conn;
20 OracleParameter parameter = command.Parameters.Add("pNsrmc", OracleType.VarChar);
21 parameter.Value = "_國%";
22 OracleDataReader reader = command.ExecuteReader();
23
24 // 以下驗證是否可以同時開啟兩個DataReader
25 OracleCommand command2 = new OracleCommand();
26 command2.CommandText = "select Count(*) from scott.nsr";
27 command2.Connection = conn;
28 OracleDataReader reader2 = command2.ExecuteReader();
29 reader2.Read();
30 Console.WriteLine("資料庫共有 {0} 個記錄。", reader2.GetInt32(0));
31 reader2.Close();
32
33 while (reader.Read())
34 {
35 if (!reader.IsDBNull(reader.GetOrdinal("Nsrmc")))
36 {
37 Console.WriteLine(reader.GetString(reader.GetOrdinal("Nsrmc")).Trim());
38 }
39// string s = null;
40// Console.WriteLine(s);
41 }
42 command.CommandText = "select count(nsrmc) from scott.nsr where nsrmc like :pNsrmc order by nsrmc";
43 Console.WriteLine("合格共有 {0} 個記錄。",command.ExecuteScalar());
44 }
45 catch (Exception e)
46 {
47 Console.WriteLine("出現了異常:{0}", e.ToString());
48 }
49 finally
50 {
51 if (conn != null)
52 {
53 conn.Close();
54 }
55 }
56
57 Console.ReadLine();
58 }
59
60 private static void OnStateChanged(object sender, StateChangeEventArgs e)
61 {
62 Console.WriteLine("資料庫連接的狀態發生改變,原狀態為:{0},目前狀態為:{1}。", e.OriginalState, e.CurrentState);
63 }
64}