在 ASP.Net 中将数据更新到 SQL Server 的最佳实践是什么
我正在 ASP.Net 中将数据更新到 SQL Server。
而且我只有一个 cs 文件,没有 aspx/ascx 文件,所以我不会在这里使用 SqlDataSource 控件。
下面是我的代码:
string connStr = ConfigurationManager.ConnectionStrings["XXConnString"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
string query = @"exec dbo.XX_Insert_Announcement @AnnID ='" + id +
"', @AnnTitle ='" + title +
"', @AnnSubmitDateTime ='" + startDate +
"', @AnnProcessDateTime ='" + endDate + "'";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
conn.Close();
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
我认为我的代码对于错误处理来说不够好,如果查询执行失败,则不会抛出错误并且代码会继续运行而不更新到数据库。
也许使用Using语句可以解决这个问题,代码如下:
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
请评论并建议什么是最佳实践。
先感谢您。
I'm doing update data into SQL Server in ASP.Net.
and I only have a cs file, no aspx/ascx file, so I'll not using the SqlDataSource control here.
Below is my code:
string connStr = ConfigurationManager.ConnectionStrings["XXConnString"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
string query = @"exec dbo.XX_Insert_Announcement @AnnID ='" + id +
"', @AnnTitle ='" + title +
"', @AnnSubmitDateTime ='" + startDate +
"', @AnnProcessDateTime ='" + endDate + "'";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
conn.Close();
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
I think my code is not good enough for error handling, if the execution of the query failed, no error is throw and the code continue running without updating to the database.
Perhaps use Using statement can solve this issue, the code as below:
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
please comment and advise on what is the best practice.
thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的第二种方法更好,但如果您使用
参数化查询来更好地防止 SQL 注入攻击
,效果会更好。Your second approach is better, but It would be better if you used a
Parameterized query for better prevention from a SQL Injection Attack
.