0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C#のメモ帳 SqlDataReaderの変数の使いまわし

Last updated at Posted at 2017-09-12

.ExecuteReader()の戻り値を格納する変数の使いまわし。
readerを一旦クローズして、改めて.ExecuteReader()の戻り値を格納してます。
見かけない書き方ですが…メモリーリークとか将来の障害とか…問題あるんでしょうかねぇ。

readerを使いまわす!
	private void button1_Click(object sender, EventArgs e)
        {

            SqlConnection conn = new SqlConnection();
            SqlCommand command = new SqlCommand();
            SqlDataReader reader;

            conn.ConnectionString = @"Data Source= … 接続文字列 …";
            conn.Open();
            command.Connection = conn;

            //1回目----------------------------------------------------------------------
            command.CommandText = "select 氏名, 所属 from ユーザマスタ where 社員番号 = '123123'";
            reader = command.ExecuteReader();

            while (reader.Read())
            {
                Console.WriteLine("氏名: {0}  所属: {1}", reader["氏名"], reader["所属"]);
            }


            reader.Close();         //<------一旦クローズ!!!


            //2回目----------------------------------------------------------------------
            command.CommandText = "select 氏名, 所属 from ユーザマスタ where 社員番号 = '456456'";
            reader = command.ExecuteReader();

            while (reader.Read())
            {
                Console.WriteLine("氏名: {0}  所属: {1}", reader["氏名"], reader["所属"]);
            }

            conn.Close();

	}

0
0
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?