iT邦幫忙

0

ASP SQL myCommand1.ExecuteReader 同時讀兩個欄位

String strSQL = @"select * from cancer_plan where pat_no=" + TextBox3.Text;
System.Data.SqlClient.SqlCommand myCommand1 = new System.Data.SqlClient.SqlCommand(strSQL, myConn1);
System.Data.SqlClient.SqlDataReader myDataReader = myCommand1.ExecuteReader();
if (myDataReader.Read())
{

            myMsg.Text = "<script>alert('已有此病歷號的規畫書!')</script><br>";
            this.Page.Controls.Add(myMsg);
        }

因為之前判斷上為單一不重複
現在要增加日期 去做同pat_no的多份存取
請問以上若要修正
要如何更改...
String strSQL = @"select * from cancer_plan where pat_no=" + TextBox3.Text + "and date=" + today.Text;
System.Data.SqlClient.SqlCommand myCommand1 = new System.Data.SqlClient.SqlCommand(strSQL, myConn1);
System.Data.SqlClient.SqlDataReader myDataReader = myCommand1.ExecuteReader();<<發生錯誤的地方
if (myDataReader.Read())
{

            myMsg.Text = "<script>alert('已有此病歷號的規畫書!')</script><br>";
            this.Page.Controls.Add(myMsg);
        }
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

4
暐翰
iT邦大師 1 級 ‧ 2018-03-19 14:11:52


這邊看下來,你的邏輯是想要where增加兩個條件?

假如上面邏輯是對的
看到你想要用字串拼接方式來組合SQL
先撇開SQL注入問題,型態是字串的要加上'
SQL server為例,Date型態也要加上'

舉例:

String sql = "select * from xxx_table where xxx_col = '"+ xxx_value +"'";
//------------------------------
String sql = "select * from xxx_table where xxx_Date = '"+ "2018-03-19" +"'";

接著解決問題:

把圖片指出地方改成以下提供的Script

String strSQL = @"select * from cancer_plan where pat_no='" + TextBox3.Text + "' and date= '" + today.Text + "'";

假如有問題再跟我說 :-)


補充:

強烈建議看完 常在面試出現的題目:SQL Injection ,了解SQL注入危險(要不然正式上線,資料庫被drop、delete會很慘的)

2
sam0407
iT邦大師 1 級 ‧ 2018-03-20 14:13:02

錯誤訊息也不PO....
暐翰大很棒,直接給了您答案,但是建議您這樣作:
先在這行程式System.Data.SqlClient.SqlCommand myCommand1 = new 上加個中斷點,然後執行程式,執行到中斷點停止時,複製strSQL的變數值,直接在資料庫管理工具上執行這行指令,將SQL指令改到可以正常出現您要的結果,再去調整您的程式。

這是很好的回答範例。
因為教人 debug 並比較困難的。

我要發表回答

立即登入回答