熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

從零開始學ASP.NET(基礎篇 連載八)

2022-06-13   來源: .NET編程 

第八天

學習目的
學會SQL中的占位符用法

在鯨魚這幾天忙死了好幾天沒寫了真對不起各位這幾天讓XHTML鬧得不開心雖然以前也知道這個但沒太在意可現在我是如夢初醒我發覺XHTML是個信號所以這幾天不得不仔細研究一下這個很笨我還沒發覺XHTML的奧妙確實如此沒上過台面真不知這桌菜怎樣好吃少說了回到正題

先把以前的Command的CommandText重新寫過

cmdCommandText = INSERT INTO NewsArticle (Title SubTitle Writer Content) VALUES ( @Title @SubTitle @Writer @Content );

這樣代碼是否很清晰了我們可以避免一大串的難以看懂的的語句了

接下來我們就給這些定位符賦予屬性和值了

cmdParametersAdd(@Title SqlDbTypeNVarChar );
cmdParametersAdd(@SubTitle SqlDbTypeNVarChar );
cmdParametersAdd(@Writer SqlDbTypeNVarChar );
cmdParametersAdd(@Content SqlDbTypeNText);

以上我們給每個占位符定義一個值類型相信不難看懂吧接者再給於值
cmdParameters[@Title]value = txtTitleTextTrim();
if (txtSubTitleText == stringEmpty || txtSubTitleTextTrim() == )
{
    cmdParameters[@SubTitle]value = DBNullvalue;
}
else
{
    cmdParameters[@SubTitle]value = txtSubTitleTextTrim();
}
if (txtWriterText == stringEmpty || txtWriterTextTrim() == )
{
    cmdParameters[@Writer]value = DBNullvalue;
}
else
{
    cmdParameters[@Writer]value = txtWriterText;
}
cmdParameters[@Content]value = txtContentText;

其實也可以這樣寫
cmdParametersAdd(@Title SqlDbTypeNVarChar ) value = txtTitleTextTrim();

這要看你喜歡了

不錯吧程序是否很有條理

程序代碼

private void btnPublish_ServerClick(object sender SystemEventArgs e)
{
    string strConnection = ConfigurationSettingsAppSettings[SqlDatabase];

    // 連接SqlServer數據庫
    SqlConnection conn = new SqlConnection(strConnection);
    // 建立SqlCommand
    SqlCommand cmd = connCreateCommand();
    cmdCommandText = INSERT INTO NewsArticle (Title SubTitle Writer Content)
                                    + valueS ( @Title @SubTitle @Writer @Content );
    connOpen();

    cmdParametersAdd(@Title SqlDbTypeNVarChar );
    cmdParametersAdd(@SubTitle SqlDbTypeNVarChar );
    cmdParametersAdd(@Writer SqlDbTypeNVarChar );
    cmdParametersAdd(@Content SqlDbTypeNText);

    cmdParameters[@Title]value = txtTitleTextTrim();
    if (txtSubTitleText == stringEmpty || txtSubTitleTextTrim() == )
    {
        cmdParameters[@SubTitle]value = DBNullvalue;
    }
    else
    {
        cmdParameters[@SubTitle]value = txtSubTitleTextTrim();
    }
    if (txtWriterText == stringEmpty || txtWriterTextTrim() == )
    {
        cmdParameters[@Writer]value = DBNullvalue;
    }
    else
    {
        cmdParameters[@Writer]value = txtWriterText;
    }
    cmdParameters[@Content]value = txtContentText;
    // 插入記錄
    try
    {
        cmdExecuteNonQuery();
    }
    catch (Exception ex)
    {
        ResponseWrite(<script language=javascript>alert(輸入錯誤數據庫不能更新)</script>);
    }
    finally
    {
        connClose();
    }
}

From:http://tw.wingwit.com/Article/program/net/201311/15759.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.