本文将建立一个最简单的WCF RIA Services访问数据库的实例,附带有数据库文件,可以在Sql
Server中附加数据库,在本文中并没有采用ADO.NET实体数据模型绑定数据库,而是单独写一个类来连接数据库查询数据表并返回值,下面我们看详细步骤。
///
<summary>
///
DB 的摘要说明
///
</summary>
public
class
DB
{
private
static
IsolationLevel m_isoLevel =
IsolationLevel.ReadUncommitted;
private
static
string
connStr =
string.Empty;
private
DB()
{
}
#region
DB2 Access Functions
static
public
IsolationLevel IsolationLevel
{
get
{
return
m_isoLevel;
}
}
///
<summary>
///
Gets Connection out of
Web.config
///
</summary>
///
<returns>Returns
SqlConnection</returns>
public
static
SqlConnection GetConnection()
{
if
(connStr ==
string.Empty)
{
AppSettingsReader
configurationAppSettings =
new
AppSettingsReader();
connStr =
"Data
Source=CXL-DC6F5F6CA80;POOLING=FALSE;database=SLRiaTest;User
ID=sa;Password=123456";
}
SqlConnection conn =
new
SqlConnection(connStr);
conn.Open();
return
conn;
}
///
<summary>
///
Gets data out of database using
a plain text string command
///
</summary>
///
<param
name="sql">string
command to be executed</param>
///
<returns>DataTable
with results</returns>
static
public
DataSet Getdata(string
sql)
{
using
(SqlConnection conn =
GetConnection())
{
using
(SqlTransaction trans =
conn.BeginTransaction(m_isoLevel))
{
try
{
using
(SqlCommand cmd =
conn.CreateCommand())
{
if
(sql !=
null)
{
sql = sql.ToLower().Replace("<;",
"");//.Replace(Convert.ToChar(32).ToString(),
" ").Replace(" ", " ").Replace("%32",
" ").Replace("%20", " ");
sql
= sql.Replace(">;",
"");
sql = sql.Replace("script",
"");
sql = sql.Replace("object",
""
sql = sql.Replace("applet",
"");
sql = sql.Replace("[",
"");
sql = sql.Replace("]",
"");
sql = sql.Replace("execute",
"");
sql = sql.Replace("exec",
"");
sql = sql.Replace("union",
"");
sql = sql.Replace("drop",
"");
sql = sql.Replace("delete",
"");
//
sql = sql.Replace("chr", "");
//sql = sql.Replace("mid", "");
sql
= sql.Replace("truncate",
"");
sql = sql.Replace("nchar",
"");
//
sql = sql.Replace("varchar",
"");
//sql = sql.Replace("char", "");
sql
= sql.Replace("alter",
"");
sql
= sql.Replace("exists",
"");
sql = sql.Replace("update",
"");
}
cmd.Transaction = trans;
cmd.CommandType =
CommandType.Text;
cmd.CommandText = sql;
using
(DataSet ds =
new
DataSet())
{
using
(SqlDataAdapter da =
new
SqlDataAdapter())
{
da.SelectCommand = cmd;
da.SelectCommand.Connection =
conn;
da.Fill(ds);
return
ds;
}
}
}
}
finally
{
trans.Commit();
}
}
}
}
#endregion
}}