我三流

いろいろ自分なりにやってみたことを書いています

C# PostgreSQL 部分一致検索するってのをやってみました。

C#のFormにCrystalReportsViewerとテキストボックスとコマンドボタンを設置して
phoneticカラムをLikeで部分一致検索するってのをやってみました。

.rptとかはできているという前提で...省略...

最初は、SelectCommandのSQL文字列にLike '%:phonetic%' とかやってみたけど動かず。。。
しばし悩んだ結果、Parameters.AddWithValueに"%"を埋め込んでやることで解決。
ただし、SQLインジェクションとか対応するにはもっと適切な方法があるんだと思う。

        private void but_name_search_Click(object sender, EventArgs e)
        {
        if (txt_phonetic.Text == null)
           {
              da.SelectCommand = new NpgsqlCommand
                (
                   "select id, name, phonetic from users_rep_view order by id", m_conn
                );
           }
           else
           {
              da.SelectCommand = new NpgsqlCommand
                (
                   "select id, name, phonetic from users_rep_view where phonetic Like :phonetic order by id", m_conn
                );
           }
        }

        if (txt_phonetic.Text == null)
           {
              da.SelectCommand.Parameters.Add(new NpgsqlParameter("phonetic",
                    NpgsqlTypes.NpgsqlDbType.Char, 0, "phonetic",
                    ParameterDirection.Input, false, 0, 0, DataRowVersion.Current,
                    DBNull.Value));

           }
           else
           {
              da.SelectCommand.Parameters.AddWithValue("phonetic", "%" + txt_phonetic.Text + "%");
           }
	
        if (ds.Tables["users_rep_view"] != null)
            ds.Tables["users_rep_view"].Clear();
        da.Fill(ds, "users_rep_view");

        Cr_users_rep myReport = new Cr_users_rep();

        myReport.SetDataSource(ds);

        Crv_users_rep.ReportSource = myReport;  
    
        }