如何使我的c#表单与oracle一起工作?

时间:2016-02-25 21:40:04

标签: c# oracle tnsnames oracle-manageddataaccess

我已经远远地搜索了StackOverflow以回答这个问题,但似乎没有什么能帮助我,所以我现在就在这里问:

所以,我有一个相当简单的形式,有几个标签和&字段和按钮。

单击该按钮后,您将对数据库执行查询。结果显示在多个字段中。当我为自己运行程序,在工作中,在Visual Studio 2013中使用F5时,使用引用Oracle.ManagedDataAccess,表单可以完美运行。

但是,当我在另一台PC上运行该程序(同一网络和所有)时,程序返回一个oracle“ORA-12154:TNS:无法解析指定的连接标识符”-error。

您应该知道的:我设置了Oracle.ManagedDataAccess,以便它使用位于c:\ Oracle \ product \ 10.2.0 \ client_1 \ network \ ADMIN的标准TNSNames.ora文件。 在工作中,网络中的每台PC都使用此位置。但是,TNSNames.ora文件并不总是像我一样完整,我可能有比其他更多的连接。这就是为什么,正如您将很快在我的代码中看到的那样,我基本上会说:"如果在位置Y的文档X中找到SID xxxxx,则不执行任何操作,否则,添加指定的必要连接信息在这里:......"

这里是我使用的涉及所有连接的代码。出于隐私原因,我用假名替换了连接细节,并将一些东西从荷兰语翻译成英语,以便您更好地理解。

由于代码很长,我只展示关于连接的部分,而且我将其他所有内容都删掉了。但正如我之前所说的那样,完整的代码只适用于我。我希望让其他人在工作中工作。

using System;

using System.Collections.Generic;   
using System.Data;    
using System.Linq;   
using System.Windows.Formss    
using System.IO;

namespace WindowsFormsApplication4
{
    public partial class GetLivingWagesV2 : Form
    {
        public GetLivingWagesV2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (comboBox1.SelectedIndex == -1)
            {
                MessageBox.Show("PLEASE SELECT AN ENVIRONMENT FIRST.");
            }

            var objtextbox = textBox1.Text;

            var ConnectionString350 = "DATA SOURCE=DATABASEPREREGRESSION01;PASSWORD=test;USER ID=REGGY";

            var ConnectionString300 = "DATA SOURCE=DATABASEREGRESSION01;PASSWORD=test;USER ID=REGGY";

            var Connection = new OracleConnection();

            if (comboBox1.SelectedIndex == 0)
            {
                var PEN300 = File.ReadAllText(@"C:\oracle\product\10.2.0\client_1\network\ADMIN\tnsnames.ora").Contains("PENREG.RSVZINASTI.BE") ? 1 : 0;

                Connection.ConnectionString = ConnectionString300;

                Connection.Open();

                var cmd = Connection.CreateCommand();

                cmd.CommandText = "SELECT DBMS_LOB.SUBSTR(b.msg_flux_in, 4000, 200) AS MSG_FLUX_IN, DBMS_LOB.SUBSTR(b.msg_flux_out, 4000, 200) AS MSG_FLUX_OUT FROM tb2b_flux a, tb2b_flux_status b where a.flux_svf_id = '" + objtextbox + "' and a.flux_id = b.flux_id order by a.dt_creatie desc";

                var Reader = cmd.ExecuteReader();


                var dt = new DataTable();

                dt.Load(Reader);

                dataGridView1.DataSource = dt;

                var column = dataGridView1.Columns[0];
                column.Width = 380;

                var column1 = dataGridView1.Columns[1];
                column1.Width = 380;

                if (PEN300 == 0)
                {
                    using (var file = new System.IO.StreamWriter(@"C:\oracle\product\10.2.0\client_1\network\ADMIN\tnsnames.ora", true))
                    {
                        file.WriteLine("DATABASEREGRESSION.ORGANISATION.BE =");
                        file.WriteLine("  (DESCRIPTION =");
                        file.WriteLine("    (ADDRESS_LIST =");
                        file.WriteLine("      (ADDRESS = (PROTOCOL = TCP)(HOST = unxin600)(PORT = 1522))");

                        file.WriteLine("    )");
                        file.WriteLine("    (CONNECT_DATA =");
                        file.WriteLine("      (SID = DATABASEREGRESSION01)");
                        file.WriteLine("    )");
                        file.WriteLine("  )");
                    }
                }
            }


            if (comboBox1.SelectedIndex == 1)
            {
                var PEN350 = File.ReadAllText(@"C:\oracle\product\10.2.0\client_1\network\ADMIN\tnsnames.ora").Contains("pendvt01.rsvzinasti.be") ? 1 : 0;

                if (PEN350 == 0)
                {
                    using (var file = new System.IO.StreamWriter(@"C:\oracle\product\10.2.0\client_1\network\ADMIN\tnsnames.ora", true))
                    {
                        file.WriteLine("DATABASEPREREGRESSION =");
                        file.WriteLine("  (DESCRIPTION =");
                        file.WriteLine("    (ADDRESS_LIST =");
                        file.WriteLine("      (ADDRESS = (PROTOCOL = TCP)(HOST = UNXPR651)(PORT = 1522))");

                        file.WriteLine("    )");
                        file.WriteLine("    (CONNECT_DATA =");
                        file.WriteLine("      (SERVICE_NAME =DATABASEPREREGRESSION01)");
                        file.WriteLine("    )");
                        file.WriteLine("  )");
                    }
                }

                else
                {
                    Connection.ConnectionString = ConnectionString350;

                    Connection.Open();

                    var cmd = Connection.CreateCommand();

                    cmd.CommandText = "SELECT DBMS_LOB.SUBSTR(b.msg_flux_in, 4000, 200) AS MSG_FLUX_IN, DBMS_LOB.SUBSTR(b.msg_flux_out, 4000, 200) AS MSG_FLUX_OUT FROM tb2b_flux a, tb2b_flux_status b where a.flux_svf_id = '" + objtextbox + "' and a.flux_id = b.flux_id order by a.dt_creatie desc";

                    var Reader = cmd.ExecuteReader();


                    var dt = new DataTable();

                    dt.Load(Reader);

                    dataGridView1.DataSource = dt;

                    var column = dataGridView1.Columns[0];
                    column.Width = 380;

                    var column1 = dataGridView1.Columns[1];
                    column1.Width = 380;
                }
            }    

            if (Connection != null && Connection.State == ConnectionState.Closed)
            {
                Connection.Open();
            }

            else
            {
                Connection.Close();
            }



            foreach (DataGridViewRow dr in dataGridView1.Rows)
            {
                foreach (DataGridViewCell dc in dr.Cells)
                {
                    if (dc.Value == null || dc.Value.ToString().Trim() == string.Empty)
                    {
                        if (dataGridView1.Rows.Count < 2)
                        {
                            MessageBox.Show("De FluxID werd niet gevonden.");
                            return;
                        }
                    }
                    else
                    {
                    }
                }
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

可能未使用tnsnames.ora文件,因为连接字符串使用EZ CONNECT(简易连接)格式。尝试修改connectionstring中的数据源:

DATA SOURCE=HOSTNAME:1521/DATABASENAME;PASSWORD=...;USER ID=...

尝试不使用tnsnames.ora对于Windows窗体应用程序是有意义的,因为它可以使分发和应用程序支持更容易。无需处理此文件,这只是一个不受您控制的外部元素,需要处理,安装和更新,这可能意味着还需要解析文件以对其进行更新,它可以更改由其他用户或其他应用程序意外。应用程序配置文件中的单行连接字符串不那么麻烦。

ODP.NET提供程序的连接字符串格式概述如下: https://www.connectionstrings.com/oracle-data-provider-for-net-odp-net/

答案 1 :(得分:0)

我建议将您的服务器信息放在web/app.config内。这样,客户甚至不需要拥有tnsnames.ora文件,甚至不需要安装oracle。

以下是您可能需要添加到web/app.config文件中以使其正常工作的部分。我通常使用.managed后缀连接名称,以确保没有命名冲突(理论上,客户端应该在web/app.config之前查看tnsnames.ora,但我不相信oracle,这使得它非常明确:)

<configuration>
    <configSections>
        <section name="oracle.manageddataaccess.client" type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
    </configSections>
    <connectionStrings>
        <add name="DbContext" connectionString="DATA SOURCE=XXXXX.managed;USER ID=XXXXX;PASSWORD=XXXXXXX;PERSIST SECURITY INFO=True;POOLING=False" providerName="Oracle.ManagedDataAccess.Client" />
    </connectionStrings>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <publisherPolicy apply="no" />
                <assemblyIdentity name="Oracle.ManagedDataAccess" publicKeyToken="89b483f429c47342" culture="neutral" />
            </dependentAssembly>
        </assemblyBinding>
    </runtime>

    <!-- add this if you use Entity Framework only -->
    <entityFramework>
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
        <providers>
            <provider invariantName="Oracle.ManagedDataAccess.Client" type="Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices, Oracle.ManagedDataAccess.EntityFramework, Version=6.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
        </providers>
    </entityFramework>
    <!-- here's the important bit, just copy descriptor from your existing tnsnames.ora file -->
    <oracle.manageddataaccess.client>
        <version number="*">
            <dataSources>
                <dataSource alias="XXXXX.managed" descriptor="(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = XXXXXX.com)(PORT = 999999))(CONNECT_DATA = (SERVICE_NAME = XXXXX)(SERVER = dedicated)))" />
            </dataSources>
        </version>
    </oracle.manageddataaccess.client>
    <system.data>
        <DbProviderFactories>
            <remove invariant="Oracle.ManagedDataAccess.Client" />
            <add name="ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client" description="Oracle Data Provider for .NET, Managed Driver" type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
        </DbProviderFactories>
    </system.data>
</configuration>

之后,您可以更改代码以使用ConfigurationManager.ConnectionStrings(或等效的版本),而不是将字符串硬编码到代码中(因为这通常是一种不好的做法)。< / p>