openDatabase Hello World

别来无恙 提交于 2019-12-21 04:59:07

问题


I'm trying to learn about openDatabase, and I think I'm getting it to INSERT INTO TABLE1, but I can't verify that the SELECT * FROM TABLE1 is working.

<html>
<head>
<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1");
</script>
<script type="text/javascript">
var db;

$(function(){
    db = openDatabase('HelloWorld');

    db.transaction(
        function(transaction) {
            transaction.executeSql(
                'CREATE TABLE IF NOT EXISTS Table1 ' +
                '  (TableID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, ' +
                '   Field1 TEXT NOT NULL );'
            );
        }
    );

    db.transaction(
        function(transaction) {
            transaction.executeSql(
                'SELECT * FROM Table1;',function (transaction, result) {
                    for (var i=0; i < result.rows.length; i++) {
            alert('1');
                        $('body').append(result.rows.item(i));
                    }
                }, 
                errorHandler
            );
        }
    );

    $('form').submit(function() {
        var xxx = $('#xxx').val();
        db.transaction(
            function(transaction) {
                transaction.executeSql(
                'INSERT INTO Table1 (Field1) VALUES (?);', [xxx], function(){
                    alert('Saved!');
                }, 
                errorHandler
                );
            }
        );
        return false;
    });
});

function errorHandler(transaction, error) {
    alert('Oops. Error was '+error.message+' (Code '+error.code+')');
    transaction.executeSql('INSERT INTO errors (code, message) VALUES (?, ?);', 
    [error.code, error.message]);
    return false;
}
</script>
</head>
<body>
<form method="post">
    <input name="xxx" id="xxx" />
    <p>
    <input type="submit" name="OK" />
    </p>
    <a href="http://www.google.com">Cancel</a>
</form>
</body>
</html>

回答1:


You're almost there, there are only two things:

  1. The if you want to use the SQL statement callback, you should supply to the executeSql method the parameters array argument, even if your query doesn't need any param.
  2. You should get a field to show in your loop, result.rows.item(i) is an object that contains properties as your table fields.

Your select will work like this:

db.transaction(function(transaction) {
  transaction.executeSql('SELECT * FROM Table1',[], function (trx, result) {
    for (var i=0; i < result.rows.length; i++) {
      $('body').append(result.rows.item(i).Field1); // <-- getting Field1 value
    }
  }, errorHandler);
});

Check your example here.



来源:https://stackoverflow.com/questions/2519844/opendatabase-hello-world

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!