js连接AWS DynamoDB数据库实现CEUD操作

柴琦
2023-12-01
  • 创建数据库
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>创建book数据库</title>
    <script src="https://sdk.amazonaws.com/js/aws-sdk-2.7.16.min.js"></script>
    <script>
        AWS.config.update({
            region: "us-west-2",
            accessKeyId: "fakeMyKeyId",//aws密钥KeyId
            secretAccessKey: "fakeSecretAccessKey"//aws密钥key
        });

        var dynamodb = new AWS.DynamoDB();

        function createMovies() {
            var params = {
                TableName : "Movies",
                KeySchema: [
                    { AttributeName: "year", KeyType: "HASH"},
                    { AttributeName: "title", KeyType: "RANGE" }
                ],
                AttributeDefinitions: [
                    { AttributeName: "year", AttributeType: "N" },
                    { AttributeName: "title", AttributeType: "S" }
                ],
                ProvisionedThroughput: {
                    ReadCapacityUnits: 5,
                    WriteCapacityUnits: 5
                }
            };

            dynamodb.createTable(params, function(err, data) {
                if (err) {
                    document.getElementById('textarea').innerHTML = "Unable to create table: " + "\n" + JSON.stringify(err, undefined, 2);
                } else {
                    document.getElementById('textarea').innerHTML = "Created table: " + "\n" + JSON.stringify(data, undefined, 2);
                }
            });
        }
    </script>
</head>

<body>
<input id="createTableButton" type="button" value="Create Table" onclick="createMovies();" />
<br><br>
<textarea readonly id= "textarea" style="width:400px; height:800px"></textarea>


</body>
</html>
  • 添加更新数据
<html>
<head>
    <script src="https://sdk.amazonaws.com/js/aws-sdk-2.7.16.min.js"></script>

    <script>
        AWS.config.update({
            region: "us-west-2",
            endpoint: 'http://localhost:8000',
            // accessKeyId default can be used while using the downloadable version of DynamoDB.
            // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
            accessKeyId: "fakeMyKeyId",
            // secretAccessKey default can be used while using the downloadable version of DynamoDB.
            // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
            secretAccessKey: "fakeSecretAccessKey"
        });
        //获取客户端
        var docClient = new AWS.DynamoDB.DocumentClient();

        function readItem() {
            var table = "Movies";
            var year = 2015;
            var title = "The Big New Movie";

            var params = {
                TableName: table,
                Key:{
                    "year": year,
                    "title": title
                }
            };
            docClient.get(params, function(err, data) {
                if (err) {
                    document.getElementById('textarea').innerHTML = "Unable to read item: " + "\n" + JSON.stringify(err, undefined, 2);
                } else {
                    document.getElementById('textarea').innerHTML = "GetItem succeeded: " + "\n" + JSON.stringify(data, undefined, 2);
                }
            });
        }

    </script>
</head>

<body>
<input id="readItem" type="button" value="Read Item" onclick="readItem();" />
<br><br>
<textarea readonly id= "textarea" style="width:400px; height:800px"></textarea>

</body>
</html>
  • 按条件更新数据
<html>
<head>
    <script src="https://sdk.amazonaws.com/js/aws-sdk-2.7.16.min.js"></script>
    <title>条件更新数据</title>
    <script>
        AWS.config.update({
            region: "us-west-2",
            endpoint: 'http://localhost:8000',
            accessKeyId: "fakeMyKeyId",
            secretAccessKey: "fakeSecretAccessKey"
        });

        var docClient = new AWS.DynamoDB.DocumentClient();

        function conditionalUpdate() {
            var table = "Movies";
            var year = 2015;
            var title = "The Big New Movie";

            // Conditional update (will fail)
            var params = {
                TableName:table,
                Key:{
                    "year": year,
                    "title": title
                },
                UpdateExpression: "remove info.actors[0]",
                ConditionExpression: "size(info.actors) > :num",//条件查询
                ExpressionAttributeValues:{
                    ":num":3
                },
                ReturnValues:"UPDATED_NEW"
            };

            docClient.update(params, function(err, data) {
                if (err) {
                    document.getElementById('textarea').innerHTML = "The conditional update failed: " + "\n" + JSON.stringify(err, undefined, 2);
                } else {
                    document.getElementById('textarea').innerHTML = "The conditional update succeeded: " + "\n" + JSON.stringify(data, undefined, 2);
                }
            });
        }

    </script>
</head>

<body>
<input id="conditionalUpdate" type="button" value="Conditional Update" onclick="conditionalUpdate();" />
<br><br>
<textarea readonly id= "textarea" style="width:400px; height:800px"></textarea>

</body>
</html>
  • 获取数据
<html>
<head>
    <script src="https://sdk.amazonaws.com/js/aws-sdk-2.7.16.min.js"></script>

    <script>
        AWS.config.update({
            region: "us-west-2",
            endpoint: 'http://localhost:8000',
            // accessKeyId default can be used while using the downloadable version of DynamoDB.
            // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
            accessKeyId: "fakeMyKeyId",
            // secretAccessKey default can be used while using the downloadable version of DynamoDB.
            // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
            secretAccessKey: "fakeSecretAccessKey"
        });

        var docClient = new AWS.DynamoDB.DocumentClient();

        function createItem() {
            var params = {
                TableName :"Movies",
                Item:{
                    "year": 2015,
                    "title": "The Big New Movie",
                    "info":{
                        "plot": "Nothing happens at all.",
                        "rating": 0
                    }
                }
            };
            //回调函数
            docClient.put(params, function(err, data) {
                if (err) {
                    document.getElementById('textarea').innerHTML = "Unable to add item: " + "\n" + JSON.stringify(err, undefined, 2);
                } else {
                    document.getElementById('textarea').innerHTML = "PutItem succeeded: " + "\n" + JSON.stringify(data, undefined, 2);
                }
            });

        }

    </script>
</head>

<body>
<input id="createItem" type="button" value="Create Item" onclick="createItem();" />
<br><br>
<textarea readonly id= "textarea" style="width:400px; height:800px"></textarea>

</body>
</html>
  • 查询数据
<html>
<head>
    <script src="https://sdk.amazonaws.com/js/aws-sdk-2.7.16.min.js"></script>

    <script>
        AWS.config.update({
            region: "us-west-2",
            endpoint: 'http://localhost:8000',
            // accessKeyId default can be used while using the downloadable version of DynamoDB.
            // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
            accessKeyId: "fakeMyKeyId",
            // secretAccessKey default can be used while using the downloadable version of DynamoDB.
            // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
            secretAccessKey: "fakeSecretAccessKey"
        });

        var docClient = new AWS.DynamoDB.DocumentClient();

        function queryData() {
            document.getElementById('textarea').innerHTML += "Querying for movies from 1985.";

            var params = {
                TableName : "Movies",
                KeyConditionExpression: "#yr = :yyyy",
                ExpressionAttributeNames:{
                    "#yr": "year"
                },
                ExpressionAttributeValues: {
                    ":yyyy":1985
                }
            };

            docClient.query(params, function(err, data) {
                if (err) {
                    document.getElementById('textarea').innerHTML += "Unable to query. Error: " + "\n" + JSON.stringify(err, undefined, 2);
                } else {
                    document.getElementById('textarea').innerHTML += "Querying for movies from 1985: " + "\n" + JSON.stringify(data, undefined, 2);
                }
            });
        }

    </script>
</head>

<body>
<input id="queryData" type="button" value="Query" onclick="queryData();" />
<br><br>
<textarea readonly id= "textarea" style="width:400px; height:800px"></textarea>

</body>
</html>
  • 扫描
<html>
<head>
    <script src="https://sdk.amazonaws.com/js/aws-sdk-2.7.16.min.js"></script>

    <script>
        AWS.config.update({
            region: "us-west-2",
            endpoint: 'http://localhost:8000',
            // accessKeyId default can be used while using the downloadable version of DynamoDB.
            // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
            accessKeyId: "fakeMyKeyId",
            // secretAccessKey default can be used while using the downloadable version of DynamoDB.
            // For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
            secretAccessKey: "fakeSecretAccessKey"
        });

        var docClient = new AWS.DynamoDB.DocumentClient();

        function scanData() {
            document.getElementById('textarea').innerHTML += "Scanning Movies table." + "\n";

            var params = {
                TableName: "Movies",
                ProjectionExpression: "#yr, title, info.rating",
                FilterExpression: "#yr between :start_yr and :end_yr",
                ExpressionAttributeNames: {
                    "#yr": "year",
                },
                ExpressionAttributeValues: {
                    ":start_yr": 1950,
                    ":end_yr": 1959
                }
            };

            docClient.scan(params, onScan);

            function onScan(err, data) {
                if (err) {
                    document.getElementById('textarea').innerHTML += "Unable to scan the table: " + "\n" + JSON.stringify(err, undefined, 2);
                } else {
                    // Print all the movies
                    document.getElementById('textarea').innerHTML += "Scan succeeded. " + "\n";
                    data.Items.forEach(function(movie) {
                        document.getElementById('textarea').innerHTML += movie.year + ": " + movie.title + " - rating: " + movie.info.rating + "\n";
                    });

                    // Continue scanning if we have more movies (per scan 1MB limitation)
                    document.getElementById('textarea').innerHTML += "Scanning for more..." + "\n";
                    params.ExclusiveStartKey = data.LastEvaluatedKey;
                    docClient.scan(params, onScan);
                }
            }
        }

    </script>
</head>

<body>
<input id="scanData" type="button" value="Scan" onclick="scanData();" />
<br><br>
<textarea readonly id= "textarea" style="width:400px; height:800px"></textarea>

</body>
</html>
 类似资料: