本文使用System.Data.OracleClient方式,这是MS提供的以ADO.NET方式访问Oracel的驱动;Oracle也有个Oracle Data Provider for .NET(ODP.NET)下篇再讨论。
访问Oracle时客户端(或者web服务器)得安装一个Oracle的客户端,这个有点不爽,SQL Server不用呀,MySQL顶多来个MySql.Data.dll 就搞定。寻觅了很久找到一个相对苗条的客户端,才12M多、小巧实用呀。安装后如下:
一个类似查询分析器的连接与查询工具,一个配置文件(很重要)。
启动连接工具
输入帐号信息,对应的是连接字符串的user id,password,datasource
连接成功后就可以查询了,这玩意看起来想windows程序,貌似像是一个dos命令行工具,输入完sql得选择"文件/运行" 执行SQL
配置文件(使用前应该先配置此文件),因为是精简版,没有图形化工具配置,所有就Notepad了
#DATABASENAME
=
# (DESCRIPTION =
# (ADDRESS_LIST =
# (ADDRESS = (PROTOCOL = TCP)(HOST = 127.0 . 0.1 )(PORT = 1521 ))
# )
# (CONNECT_DATA =
# (SERVICE_NAME = servicename)
# )
# )
# (DESCRIPTION =
# (ADDRESS_LIST =
# (ADDRESS = (PROTOCOL = TCP)(HOST = 127.0 . 0.1 )(PORT = 1521 ))
# )
# (CONNECT_DATA =
# (SERVICE_NAME = servicename)
# )
# )
更改这个注释过的例子配置
myOracle
=
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = 33.33 . 33.33 )(PORT = 1521 ))
)
(CONNECT_DATA =
(SERVICE_NAME = mysid)
)
)
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = 33.33 . 33.33 )(PORT = 1521 ))
)
(CONNECT_DATA =
(SERVICE_NAME = mysid)
)
)
其中,myOracle是随便起的名子,连接字符串的data source=这里的myOracle;HOST,PORT不用说了;SERVICE_NAME = mysid 填服务端数据库实例的SID,这里应该是确定了那个数据库了。
配置完成后就可以在程序中访问Oracle,以下举例获取一个表的数据显示在页面
using System.Data.OracleClient;
OracleConnection con
=
new
OracleConnection(
"
Data Source=myOracle;user id=xxx;password=xxx;
"
);
OracleCommand cmd = new OracleCommand( " select * from table " , con);
con.Open();
OracleDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
GridView1.DataSource = dr;
GridView1.DataBind();
dr.Close();
OracleCommand cmd = new OracleCommand( " select * from table " , con);
con.Open();
OracleDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
GridView1.DataSource = dr;
GridView1.DataBind();
dr.Close();
--
显示所有表信息,类似mysql的show tables
select * from all_tables
-- 显示前几条,类似sqlserver的select top
select * from tb WHERE ROWNUM <= 5
-- from表名应该为OWNER.TABLE_NAME
select * from ms.mytable
-- 参数符号不同,oracle中为: sqlserver中为@ mysql中为?
select * from tab where id = :myid
select * from all_tables
-- 显示前几条,类似sqlserver的select top
select * from tb WHERE ROWNUM <= 5
-- from表名应该为OWNER.TABLE_NAME
select * from ms.mytable
-- 参数符号不同,oracle中为: sqlserver中为@ mysql中为?
select * from tab where id = :myid