从C#向Access数据库发送字符串值

时间:2015-06-06 20:11:38

标签: c# sql-server

我使用C#

进行以下查询
string sqlQuery = "select userinfo.badgenumber, userinfo.name, userinfo.ssn, checkinout.checktime, IIF(checkinout.checktype = 'O','Clock Out','Clock In') as checktype from checkinout, userinfo, machines where userinfo.userid = checkinout.userid";
if (!String.IsNullOrEmpty(fromDate) && !String.IsNullOrEmpty(toDate))
{
    sqlQuery += " and checkinout.checktime between #" + fromDate + " 00:00:00# and #" + toDate + " 23:59:59#";
}
if (!String.IsNullOrEmpty(title))
{
    sqlQuery += " and userinfo.title in (" + title + ")";
}
if (!String.IsNullOrEmpty(empId))
{
    sqlQuery += " and checkinout.userid in (" + empId + ")";
}

当我调试它时,它会提供以下数据库查询。

select userinfo.badgenumber, userinfo.name, userinfo.ssn, checkinout.checktime, IIF(checkinout.checktype = 'O','Clock Out','Clock In') as checktype from checkinout, userinfo, machines where userinfo.userid = checkinout.userid and checkinout.checktime between #12/28/2014 00:00:00# and #06/07/2015 23:59:59# and userinfo.title in (Manager,Sales) and checkinout.userid in (52,14,4) order by checkinout.userid, checkinout.checktime

一切正常,只有一个问题,我需要在字符串周围使用单个引号。它应该是('经理','销售'),但查询使它(经理,销售)或我是否使用此

if (!String.IsNullOrEmpty(title))
{
    sqlQuery += " and userinfo.title in (" + "'" + title + "'" + ")";
}

它给我这样的结果('经理,销售')。

3 个答案:

答案 0 :(得分:1)

您的title似乎是Manager, Sales,并希望将其作为'Manager', 'Sales',一种方式是string.JoinSelect方法的组合,例如; < / p>

var newTitle = string.Join(",", title.Split(',').Select(s => string.Format("'{0}'", s)));
// newTitle is 'Manager',' Sales'

这里有 demonstration

答案 1 :(得分:0)

不要将它们作为带有串联sql命令的字符串发送。

使用参数化查询,这样就可以避免sql注入。

http://www.dreamincode.net/forums/topic/268104-parameterizing-your-sql-queries-the-right-way-to-query-a-database/

答案 2 :(得分:0)

我找到了结果。这只是替换功能的使用。

string strTitle = "'" + title.Replace(",", "','") + "'";