Oracle 10G的安裝請見上一篇文章,現在是安裝後測試一下串連的效果
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OracleClient;
namespace Nhibernate1
{
public partial class FormOracle : Form
{
private System.Data.OracleClient.OracleConnection con;
private System.Data.OracleClient.OracleDataAdapter adapter;
private System.Data.OracleClient.OracleCommand cmd;
private System.Data.DataSet ds;
public FormOracle()
{
InitializeComponent();
}
private void FormOracle_Load(object sender, EventArgs e)
{
openCon();
DataSet ds = GetDataSet(" select empno,ename,job from scott.emp");
this.dataGridView1.DataSource = ds.Tables[0];
}
private void openCon()
{
try
{
if (this.con == null)
{
//使用using可以使該串連可以調用Dispose方法來釋放資源
//using (this.con = new OracleConnection())
//{
this.con = new OracleConnection();
//設定資料庫連接屬性為web.config中的設定的值(預設)
//或者設定為建構函式中指定的connString的值
this.con.ConnectionString
= "Data Source=orcl;User ID=scott;Password=tiger;Unicode=True";
this.con.Open();
//}
System.Console.Write("資料庫連接成功!"); //Test
}
else if (con.State == ConnectionState.Closed)
{
this.con.Open();
}
}
catch
{
System.Console.Write("資料庫連接失敗,請與管理員聯絡!");
}
}
public System.Data.DataSet GetDataSet(string sql)
{
this.adapter = new OracleDataAdapter();
this.ds = new DataSet();
this.CreateCmd(sql);
this.adapter.SelectCommand = this.cmd;
this.adapter.Fill(this.ds);
return this.ds;
}
private void CreateCmd(string sql)
{
//方法1
this.cmd = new OracleCommand();
this.cmd.Connection = this.con;
this.cmd.CommandText = sql;
}
private void button1_Click(object sender, EventArgs e)
{
}
}
}