When opening an oracle connection, connection object is null

后端 未结 5 2086
予麋鹿
予麋鹿 2020-12-19 10:08

I am trying to connect to an oracle database in my controller:

 using Oracle.DataAccess.Client;
 using Oracle.DataAccess.Types;

 // Other code

 OracleConne         


        
5条回答
  •  失恋的感觉
    2020-12-19 10:29

    I had the same problem when I started to use ODP.NET.

    You can adjust your code like this:

    try
    {
        OracleConnection con;
        con = new OracleConnection();
    
        con.ConnectionString = "DATA SOURCE=;PERSIST SECURITY INFO=True;USER ID=******;PASSWORD=*******";
    
        con.Open();
    }
    catch (OracleException ex)
    {
        Console.WriteLine("Oracle Exception Message");
        Console.WriteLine("Exception Message: " + ex.Message);
        Console.WriteLine("Exception Source: " + ex.Source);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception Message");
        Console.WriteLine("Exception Message: " + ex.Message);
        Console.WriteLine("Exception Source: " + ex.Source);
    }
    

    You can get more information about your error here: ORA-12154

    The problem is your Data Source in your connection string. I assume that it looks like this: Data Source=Server.Source as you could find in your TNSNAMES.ORA file on your computer.

    The problem is that ODP.NET does not read the TNSNAMES.ORA file as Visual Studio does.

    You have multiple choices to solve this issue:

    1. Edit your Web.Config or App.config file to tell ODP.NET how to handle your source.
    2. Copy your TNSNAMES.ORA file in the same directory as the .exe. (If it's not a web app)
    3. Change the Data Source in order to write the long version instead of the alias. E.g. : Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=sales-server)......)))

    My favorite method is the #3. It's a lot easier to debug when you have a problem.

    You can find more information in the dataSources Section of the Configuring Oracle Data Provider for .NET documentation.

提交回复
热议问题