【发布时间】:2013-12-18 21:26:57
【问题描述】:
作为我在所有业务应用程序中使用的常用实用程序的一部分,我有这段代码...
using System.Web.UI.WebControls;
public class Database
{
/// <summary>
/// Creates a DataView object using the provided query and an SqlDataSource object.
/// </summary>
/// <param name="query">The select command to perform.</param>
/// <returns>A DataView with data results from executing the query.</returns>
public static DataView GetDataView(string query)
{
SqlDataSource ds = GetDBConnection();
ds.SelectCommand = query;
DataView dv = (DataView)ds.Select(DataSourceSelectArguments.Empty);
return dv;
}
/// <summary>
/// Creates a SqlDataSource object with initialized connection string and provider
/// </summary>
/// <returns>An SqlDataSource that has been initialized.</returns>
public static SqlDataSource GetDBConnection()
{
SqlDataSource db = new SqlDataSource();
db.ConnectionString = GetDefaultConnectionString(); //retrieves connection string from .config file
db.ProviderName = GetDefaultProviderName(); //retrieves provider name from .config file
return db;
}
}
然后,在我的项目中,为了从数据库中检索数据,我将编写一些代码,例如..
DataView dv=Database.GetDataView("select mycolumn from my table");
//loop through data and make use of it
我因以这种方式使用 SqlDataSource 而受到了人们的关注。人们似乎不喜欢我纯粹从代码中使用 Web 控件,而不是将其放在 ASPX 页面上。这对他们来说看起来不对,但他们无法告诉我不利的一面。那么,有缺点吗?这是我的主要问题。因为如果有很多缺点,我可能不得不改变我开发许多内部应用程序的方式。
只要我添加 System.Web 程序集,我的 Database 类甚至可以在非 ASP.NET 情况下工作。我知道包大小略有增加,但我觉得对于我正在编写的应用程序类型来说这是值得的。从 WPF/Windows 窗体/控制台程序中使用 SqlDataSource 是否有缺点?
【问题讨论】:
-
此代码是您真实代码的简化版本,还是您从不向查询传递参数?因为你贴出来的代码好像是邀请SQL Injection如果需要传参数的话。
-
@RichardDeeming Simplified,我还有其他代码可以清理 SQL 注入。我想我应该提一下,这段代码用于我们 60 人公司的内部业务线应用程序。它不公开。
-
内部用户不可能试图破解您的数据库或恶意软件进入您的网络,对吧? troyhunt.com/2013/10/your-corporate-network-is-already.html
-
@RichardDeeming 我并不是说不可能。我是说我会采取措施防范它,而且它不像公共网站那样令人担忧。
标签: c# asp.net .net sqldatasource