MS Access,Javascript SQL“Where” - 查询

时间:2015-11-20 16:30:02

标签: ms-access client-side jscript

我坚持使用JS从MS Access数据库中获取数据的简单查询。 连接和其他一切正常。

sql_query =“SELECT * FROM tblname WHERE [tbl_1] .dshb_name ='”+ showDashboard +“'AND [tbl_2] .monkpi_name ='”+ showKPI +“'AND [tbl_3] .mnth =”+ DateValueHere +“”; < / p>

当我删除包含日期的第二个AND部分时,一切正常。

我在查询表达式中得到“语法错误(缺少运算符)”。

1 个答案:

答案 0 :(得分:1)

您应该使用参数化查询,如下所示:

var adDate = 7;
var adVarWChar = 202;
var adParamInput = 1;

// test data
var showDashboard = "test_dshb";
var showKPI = "test_kpi";
var dateValueHere = new Date(2015, 10, 20);  // November 20, 2015

var conn = new ActiveXObject("ADODB.Connection");
conn.Open( 
        "Provider=Microsoft.ACE.OLEDB.12.0;" +
        "Data Source=C:\\Users\\Public\\Database1.accdb;"
        );
var cmd = new ActiveXObject("ADODB.Command");
cmd.ActiveConnection = conn;
cmd.CommandText = 
        "SELECT * FROM tblname " +
        "WHERE dshb_name=? AND monkpi_name=? AND mnth=?";
cmd.Parameters.Append(cmd.CreateParameter("?", adVarWChar, adParamInput, 255));
cmd.Parameters.Append(cmd.CreateParameter("?", adVarWChar, adParamInput, 255));
cmd.Parameters.Append(cmd.CreateParameter("?", adDate, adParamInput));

cmd.Parameters(0).Value = showDashboard;
cmd.Parameters(1).Value = showKPI;
cmd.Parameters(2).Value = dateValueHere.getVarDate();
var rst = cmd.Execute();
while (!rst.EOF) {
    WScript.Echo(rst(0).Value);
    rst.MoveNext();
}

rst.Close();
conn.Close();

如果您想要检索整个月的结果,那么您可以采用的一种方式是

var adDate = 7;
var adVarWChar = 202;
var adParamInput = 1;

// test data
var showDashboard = "test_dshb";
var showKPI = "test_kpi";
var dateValueHere = new Date(2015, 0, 1);  // January 1, 2015

var conn = new ActiveXObject("ADODB.Connection");
conn.Open( 
        "Provider=Microsoft.ACE.OLEDB.12.0;" +
        "Data Source=C:\\Users\\Public\\Database1.accdb;"
        );
var cmd = new ActiveXObject("ADODB.Command");
cmd.ActiveConnection = conn;
cmd.CommandText = 
        "SELECT * FROM tblname " +
        "WHERE dshb_name=? AND monkpi_name=? " +
            "AND mnth>=? AND mnth<DateAdd('m', 1, ?)";
cmd.Parameters.Append(cmd.CreateParameter("?", adVarWChar, adParamInput, 255));
cmd.Parameters.Append(cmd.CreateParameter("?", adVarWChar, adParamInput, 255));
cmd.Parameters.Append(cmd.CreateParameter("?", adDate, adParamInput));
cmd.Parameters.Append(cmd.CreateParameter("?", adDate, adParamInput));

cmd.Parameters(0).Value = showDashboard;
cmd.Parameters(1).Value = showKPI;
cmd.Parameters(2).Value = dateValueHere.getVarDate();
cmd.Parameters(3).Value = dateValueHere.getVarDate();
var rst = cmd.Execute();
while (!rst.EOF) {
    WScript.Echo(rst(0).Value);
    rst.MoveNext();
}

rst.Close();
conn.Close();