在asp.net mvc

时间:2018-03-12 11:21:29

标签: c# asp.net asp.net-mvc oracle11g connection-string

这是我的数据库连接类。我想访问' oracleCommand'来自另一个类的对象引用。

public class DBConnection
        { 
            //public OracleCommand oracleCommand;
            public string cmd = "";
            public void makeConnection()
            {
                //Opening connection
                string connectionString = "XXXX";
                OracleConnection con = new OracleConnection();
                con.ConnectionString = connectionString;
                con.Open();
                OracleCommand oracleCommand = con.CreateCommand();
                cmd = oracleCommand.CommandText;
                //Clossing resources
                con.Close();
                oracleCommand.Dispose();
            }

然后我想执行以下查询。

dbConnection.cmd = "SELECT COUNT(JOB_ID) FROM EmployeeTable WHERE STATUS='Pending'";
                OracleDataReader Reader = dbConnection.oracleCommand.ExecuteReader();
                Reader.Read();

但是' dbConnection.oracleCommand.ExecuteReader()'调试时没有命中。有没有人有想法?

1 个答案:

答案 0 :(得分:1)

您将成员oracleCommand隐藏在makeConnection - 方法中存在的名称相同的变量中。在你的方法中省略声明:

public class DBConnection
{ 
    public OracleCommand oracleCommand;
    public string cmd = "";
    public void makeConnection()
    {
        //Opening connection
        string connectionString = "XXXX";
        OracleConnection con = new OracleConnection();
        con.ConnectionString = connectionString;
        con.Open();
        this.oracleCommand = con.CreateCommand(); // here
        cmd = oracleCommand.CommandText;
        //Clossing resources
        con.Close();
        oracleCommand.Dispose();
    }

然而,由于您无法对命令执行任何操作,因此对您没有多大帮助,因为在makeConnection运行后您将对其进行处理。

此外,甚至向外部公开命令也是一个坏主意。您应该公开连接并为要在db上执行的每个语句创建一个新命令:

public class DBConnection
{ 
    public OracleConnection { get; private set; }
    public string cmd = "";
    public void makeConnection()
    {
        //Opening connection
        string connectionString = "XXXX";
        this.Connection = new OracleConnection();
        this.Connection.ConnectionString = connectionString;
        con.Open();
    }

现在创建第二个执行查询并返回结果的方法:

public int CountPendingElements()
{
    using(var cmd = this.Connection.CreateCommand())
    {
        cmd.CommandText = "SELECT COUNT(JOB_ID) FROM EmployeeTable WHERE STATUS='Pending'";
        OracleDataReader Reader = cmd.ExecuteReader();
        Reader.Read();
        return reader.GetInt32(0);
    }
}

using - 语句确保即使在代码块中发生异常的情况下也会处理该命令。

除此之外,您的课程应该实现IDisposable以在您完成它时处置其基础连接。