Oracle数据库多行 - > C#

时间:2017-08-18 06:38:46

标签: c# oracle

如何使用c#.net从oracle数据库中检索多个数据行?并将数据行显示在列表框中。

2 个答案:

答案 0 :(得分:1)

让我们刷你的代码:

// Extract methods, don't cram everything in OnClick
private void FeedFriendsListBox() {
  string oracleDb = @"connection string";

  //DONE: wrap IDisposable into using
  using (OracleConnection conn = new OracleConnection(oracleDb)) {
    conn.Open();

    //DONE: Make Sql readable - format it out and use names for the parameter(s)
    string sql =
      @"SELECT NAME, 
               ADDRESS  
          FROM FRIENDS 
         WHERE AGE = :prm _Age";

    //DONE: wrap IDisposable into using
    using (OracleCommand cmd = new OracleCommand(sql, conn)) {
      cmd.Parameters.Add(new OracleParameter(txtlist.Text, OracleDbType.Decimal));

      //DONE: wrap IDisposable into using 
      using (var reader = cmd.ExecuteReader()) {
        if (!reader.HasRows) {
          listBox1.Text = "Not Found";

          MessageBox.Show("Data Not found", "NOT FOUND", 
                           MessageBoxButtons.OK, MessageBoxIcon.Information);

          return;
        }

        //DONE: Value is zero based
        //DONE: use formatting (string interpolation), not concatenating
        while (reader.Read())
          listBox1.Items.Add($"{reader.GetValue(0)} from {reader.GetValue(1)}");
      }
    }
  }
}

然后使用提取的方法:

private void button2_Click(object sender, EventArgs e) {
  FeedFriendsListBox();   
} 

答案 1 :(得分:-2)

private void button2_Click(object sender, EventArgs e)
        {
            //database connection string and opening area
            string oracleDb = @"connection string";
            OracleConnection conn = new OracleConnection(oracleDb);
            conn.Open();

            //declareing paramater and readning parameter input
            OracleParameter param = new OracleParameter();
            param.OracleDbType = OracleDbType.Decimal;
            param.Value = txtlist.Text;

            OracleCommand cmd = new OracleCommand();
            cmd.Connection = conn;

            //sendting the parameter to the tabase query 
            cmd.Parameters.Add(param);
            cmd.CommandText = "SELECT NAME, ADDRESS  FROM FRIENDS WHERE age = :1";

            cmd.CommandType = CommandType.Text;
            OracleDataReader dataread = cmd.ExecuteReader();
            dataread.Read();

            if (dataread.HasRows)
            {
                while (dataread.Read())
                {
                    listBox1.Items.Add(dataread.GetString(1) + " from " + dataread.GetString(2));
                }
            }
            else
            {
                listBox1.Text = "Not Found";
                MessageBox.Show("Data Not found", "NOT FOUND", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            conn.Dispose();
        }