码迷,mamicode.com
首页 > 数据库 > 详细

Oracle_C#连接Oracle数据库

时间:2020-04-22 13:11:47      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:dmi   oracle数据库   open()   data   string   select   roc   技术   exception   

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;
        }

Oracle_C#连接Oracle数据库

标签:dmi   oracle数据库   open()   data   string   select   roc   技术   exception   

原文地址:https://www.cnblogs.com/bigmonk/p/12750815.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!