SQL

SQL插入语句不适用于Javascript

发布于 2021-05-10 21:28:41

我正在尝试使用JSON数组填充WebSQL数据库(对象称为myJSONObject,数组称为costcodes)。

该函数在单击时运行,数据库成功创建,但是数据未插入数据库中。它甚至不抛出错误,它什么也没做。

我最初的想法是无法正确地转义数据,但是我不知道确切的位置/方式。所以我很困惑。

    localDB = null;

    function initDB()
    {
        if (localDB==null)
        {
            var shortName = 'Costcode';
            var version = '1.0';
            var displayName = 'Costcode';
            var maxSize = 217802; // in bytes
            localDB = window.openDatabase(shortName, version, displayName, maxSize);
        }

    }
            function buildTable()
    {
       var sQuery = 'CREATE TABLE IF NOT EXISTS Costcode ('+
                    'id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,' +
                    'cost_code_no VARCHAR NULL,' +
                    'row_unique_no VARCHAR NULL,' +
                    'cost_class_no VARCHAR NULL,' +
                    'Table_Version VARCHAR DEFAULT "1.0");';
        try
        {
            initDB();
            localDB.transaction(function(transaction)
            {
                transaction.executeSql(sQuery, []);
                console.log('sucess');
            });
        }
        catch (e)
        {
           alert("Error: Unable to create table 'x" + "' " + e + ".");
           return;
       }    
    }


 function exeSQLFast()
    {

                initDB();
                localDB.transaction(function(transaction)
                {
                    for (var x = 0; x <myJSONObject.costcodes.length; x++)
                    {

                        var costcodeno = myJSONObject.costcodes[x].cost_code_no;
                        var rowuniqueid = myJSONObject.costcodes[x].row_unique_id;
                        var costclassno = myJSONObject.costcodes[x].cost_class_no;
                        console.log(costcodeno);
                        console.log(rowuniqueid); 
                        console.log(costclassno);
                    transaction.executeSql('INSERT INTO Costcode (cost_code_no, row_unique_id, cost_class_no) VALUES (? , ? , ?)',
                     [costcodeno,
                     rowuniqueid,
                     costclassno]
                     , function(transaction, results)
                        {
                            console.log(costcodeno);
                            console.log('hooray');
                        }

                    )};
                    }
            )}

</script>
</head>

<body onLoad="buildTable();">
<input type="button" onClick="exeSQLFast();" value='button'>
</body>
</html>

控制台日志显示所有变量均已正确定义,但未运行insert语句。有任何想法吗?

这是一个例子 myJSONObject.costcodes[2]

cost_class_no: "    3"
cost_code_no: "      1000"
row_unique_id: 335

看起来好像不是问题…

关注者
0
被浏览
61
1 个回答
  • 面试哥
    面试哥 2021-05-10
    为面试而生,有面试问题,就找面试哥。

    问题是我在插入语句中调用了row_unique_no列row_unique_id。现在我觉得很蠢。

    但是,如果有人好奇如何正确填充WebSQL数据库,这就是您的方法。只是不要输入错误的列名。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看