和OCI, PRO*C, JDBC连接Timesten一样,.NET连接TimesTen也非常简单。只不过需要安装的组件比较多些而已。
在运行示例程序之前,需要在Windows上先安装:
1. TimesTen Windows客户端,本例中,由于TimesTen数据库在Windows上,因此完整安装TimesTen
2. Oracle Database or Oracle Data Access Components (ODAC),其中包含了ODP.NET 12.1
3. Miicrosoft Visual Studio,免费的社区版即可
由于.NET是基于OCI的,OCI的驱动已经包含在TimesTen客户端安装中了。
TimesTen文档中与.NET相关的只有一个PDF: Oracle? Data Provider for .NET - Oracle TimesTen In-Memory Database Support User’s Guide, 仅28页,说明绝大部分的内容都与连接Oracle相同。
在TimesTen安装目录下的quickstart/sample_code/odp.net下有示例程序DemoODP.cs, 不过为了简便,我还是提供了一个HelloWorld.cs程序,尽管我从未写过C#代码,感觉和Java有点像。
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;
using System.Data;
using System.Data.Common;
public class HelloWorld
{
private static string connStr = "";
private OracleConnection conn = null;
public HelloWorld ()
{
OracleCommand crtab = null;
OracleCommand insert = null;
OracleCommand select = null;
OracleDataReader reader = null;
try
{
conn = new OracleConnection ();
conn.ConnectionString = connStr;
conn.Open ();
crtab = new OracleCommand ("create table a(a int)", conn);
crtab.CommandType = CommandType.Text;
crtab.ExecuteNonQuery ();
crtab.Dispose ();
insert = new OracleCommand ("insert into a values(1)", conn);
insert.CommandType = CommandType.Text;
insert.ExecuteNonQuery ();
insert.Dispose ();
select = new OracleCommand("select max(a) from a", conn);
select.CommandType = CommandType.Text;
reader = select.ExecuteReader();
if (reader.Read())
{
object[] values = new object[1];
reader.GetValues(values);
if (values[0] != DBNull.Value)
{
Console.WriteLine ("Fetched Value is: " + Convert.ToInt32(values[0]));
}
}
reader.Close();
select.Dispose();
conn.Close ();
conn.Dispose ();
}
catch (Exception e)
{
Console.WriteLine ("Test Failed");
Console.WriteLine (e.Message);
Console.WriteLine (e.StackTrace);
Environment.Exit (-1);
}
}
public static void Main (string[]args)
{
connStr =
//"Data Source=sampledb_1122; user id=appuser; password=appuser";
"Data Source=localhost/sampledb_1122:timesten_direct;user id=appuser; password=appuser";
new HelloWorld ();
}
}
源代码中最关键的是Main中的connStr,可以是TNS形式,即:
connStr = "Data Source=sampledb_1122; user id=appuser; password=appuser";
也可以是easy connect形式:
connStr = "Data Source=localhost/sampledb_1122:timesten_direct;user id=appuser;
进入 “开发人员命令提示”
设置TNS_ADMIN,此路径下有tnsnames.ora文件:
set TNS_ADMIN=D:\TimesTen\tt1122_64\network\admin
我们需要的TNS服务为:
SAMPLEDB_1122 =(DESCRIPTION=(CONNECT_DATA =
(SERVICE_NAME = SAMPLEDB_1122)(SERVER = timesten_direct)))
编译:
csc /out:HelloWorld.exe /reference:D:\app\client\yyxiao\product\12.1.0\client_1\odp.net\bin\4\Oracle.DataAccess.dll HelloWorld.cs
其中D:\app\client\yyxiao\product\12.1.0\client_1\odp.net\bin\4\Oracle.DataAccess.dll
为ODAC驱动文件
运行程序: