Oracle_C#连接Oracle数据库
1、确保已安装Oracle客户端,已创建数据库
2、在项目中安装Oracle.ManagedDataAccess Nuget包
在vs中工具——Nuget包管理器——管理解决方案的Nuget程序包——搜索安装即可(确保联网)
3、添加引用using Oracle.ManagedDataAccess.Client;
4、创建查询方法
确定连接字符串:
Data Source:数据源
可在Oracle安装目录 C:\app\Admin\product\11.2.0\dbhome\NETWORK\ADMIN下tnsnames.ora中找到,记事本打开如下:
# tnsnames.ora Network Configuration File: C:\app\Admin\product\11.2.0\dbhome\network\admin\tnsnames.ora
# Generated by Oracle configuration tools.
LISTENER_ORCL =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
ORACLR_CONNECTION_DATA =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
)
(CONNECT_DATA =
(SID = CLRExtProc)
(PRESENTATION = RO)
)
)
ORCL =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = orcl)
)
)
连接字符串Data Source为最后一部分
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = orcl)
)
)
User Id:用户名
Password:安装时设置的口令(密码)
public DataTable ExportDataTable(string tableName, string selectStr)
{
DataTable dt = new DataTable();
if (selectStr == "" || selectStr == null)
{
selectStr = "1=1";
}
try
{
using (OracleConnection con = new OracleConnection("Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = orcl)));User Id=system;Password=147258"))
{
con.Open();
string cmdStr = $"select * from {tableName} where {selectStr}";
OracleCommand command = new OracleCommand(cmdStr, con);
OracleDataAdapter adapter = new OracleDataAdapter(command);
adapter.Fill(dt);
}
}
catch (Exception)
{
throw;
}
return dt;
}