4

我的问题与此类似,我如何使用 OracleDataReader 检索给定记录的所有字段?目前,我一直在使用这种方法,它一次只返回一个列值:

public string Select_File(string filename, string subdirectory, string envID)
{
    Data_Access da = new Data_Access();
    OracleConnection conn = da.openDB();

    OracleCommand cmd = new OracleCommand();
    cmd.Connection = conn;
    cmd.CommandText = "SELECT * FROM EIP_Deployment_Files" 
        + " WHERE Filename ='" + filename + "'"
        + " AND Subdirectory = '" + subdirectory + "'"
        + " AND Environment_ID = '" + envID + "'";
    cmd.CommandType = CommandType.Text;

    string x;
    OracleDataReader dr = cmd.ExecuteReader();
    if (dr.HasRows) // file exists in DB
    {
        dr.Read();
        x = dr.GetString(2).ToString(); // return baseline filename (index 2)
    }
    else
    {
        x = "New File";
    }

    cmd.Dispose();
    da.CloseDB(conn);
    return x;
}

我确信这种方法远非完美,人们会很快指出这一点(我基本上是由我的主管给的,因为我之前没有任何 ASP.NET 经验)但我真正关心的是它的工作原理。我的问题是:如何修改它以返回给定记录的所有字段?

这些字段将是 VARCHAR2、CHAR 或 DATE 数据类型(如果有区别的话),其中一些值可能为空。我在想我可以将它们转换为字符串并将它们作为列表返回吗?

4

3 回答 3

10

如果你想要这样的东西:

List<User> lstUser = new List<User>();
            string sqlQuery = "Select * from User_T where User_Name='" + oUser.UserName + "' And Password='" +oUser.Password + "' AND IsActive='"+1+"' AND IsDelete='"+0+"'";
            string connectionString = "Data Source=ORCL;User Id=ACCOUNTS;Password=ACCOUNTS";
            using (DBManager dbManager = new DBManager(connectionString))
            {
                try
                {

                    dbManager.Open();
                    OracleDataReader dataReader = dbManager.ExecuteDataReader(sqlQuery);
                    while (dataReader.Read())
                    {
                        oUser = new User();
                        oUser.Id = Convert.ToInt32(dataReader["ID"]);
                        oUser.CompanyId = Convert.ToInt32(dataReader["Company_ID"]);
                        oUser.BranchId = Convert.ToInt32(dataReader["Branch_ID"]);
                        oUser.UserName = Convert.ToString(dataReader["User_Name"]);
                        lstUser.Add(oUser);
                    }
                    dataReader.Close();
                    dataReader.Dispose();

                }
                catch
                (Exception)
                {


                }
                finally
                {
                    dbManager.Close();
                    dbManager.Dispose();
                }
于 2013-04-25T20:25:29.417 回答
6

To read all the data from the columns of the current row in a DataReader, you can simply use GetValues(), and extract the values from the array - they will be Objects, of database types.

Object[] values;
int numColumns = dr.GetValues(values); //after "reading" a row
for (int i = 0; i < numColumns; i++) {
    //read values[i]
}

MSDN - "For most applications, the GetValues method provides an efficient means for retrieving all columns, rather than retrieving each column individually."

于 2013-04-25T18:59:27.770 回答
4

很抱歉发布一个非常古老的问题的答案。由于没有一个答案是正确的(他们有安全问题或没有检查 DBNull),我决定发布我自己的答案。

public async Task<StringBuilder> FetchFileDetailsAsync(string filename, string subdirectory, string envId)
    {
        var sb = new StringBuilder();
        //TODO: Check the parameters

        const string connectionString = "user id=userid;password=secret;data source=" +
                                        "(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=10.0.0.8)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=xe)))";

        const string selectQuery = "SELECT * FROM EIP_Deployment_Files"
                                + " WHERE Filename = :filename"
                                + " AND Subdirectory = :subdirectory"
                                + " AND Environment_ID = :envID"
                                + " AND rownum<=1";

        using (var connection = new OracleConnection(connectionString))
        using (var cmd = new OracleCommand(selectQuery, connection) {BindByName = true, FetchSize = 1 /*As we are expecting only one record*/})
        {

            cmd.Parameters.Add(":filename", OracleDbType.Varchar2).Value = filename;
            cmd.Parameters.Add(":subdirectory", OracleDbType.Varchar2).Value = subdirectory;
            cmd.Parameters.Add(":envID", OracleDbType.Varchar2).Value = envId;

            //TODO: Add Exception Handling
            await connection.OpenAsync();
            var dataReader = await cmd.ExecuteReaderAsync(CommandBehavior.CloseConnection);

            var rowValues = new object[dataReader.FieldCount];
            if (dataReader.Read())
            {
                dataReader.GetValues(rowValues);
                for (var keyValueCounter = 0; keyValueCounter < rowValues.Length; keyValueCounter++)
                {
                    sb.AppendFormat("{0}:{1}", dataReader.GetName(keyValueCounter), 
                        rowValues[keyValueCounter] is DBNull ? string.Empty : rowValues[keyValueCounter])
                      .AppendLine();
                }

            }
            else
            {
                //No records found, do something here
            }
            dataReader.Close();
            dataReader.Dispose();
        }
        return sb;
    }
于 2017-01-27T11:45:02.537 回答