第八天
学习目的
学会SQL中的占位符用法
在鲸鱼这几天忙死了好几天没写了真对不起各位这几天让XHTML闹得不开心虽然以前也知道这个但没太在意可现在我是如梦初醒我发觉XHTML是个信号所以这几天不得不仔细研究一下这个很笨我还没发觉XHTML的奥妙确实如此没上过台面真不知这桌菜怎样好吃少说了回到正题
先把以前的Command的CommandText重新写过
cmd
CommandText =
INSERT INTO NewsArticle (Title
SubTitle
Writer
Content) VALUES ( @Title
@SubTitle
@Writer
@Content )
;
这样代码是否很清晰了我们可以避免一大串的难以看懂的的语句了
接下来我们就给这些定位符赋予属性和值了
cmd
Parameters
Add(
@Title
SqlDbType
NVarChar
);
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();
这要看你喜欢了
不错吧程序是否很有条理
程序代码
privatevoid btnPublish_ServerClick(object sender
System
EventArgs 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();
}
}