To use a database in PhoneGap, you can utilize the HTML5 Web SQL Database API or the IndexedDB API. These databases allow you to store data locally on the user's device.
Using Web SQL Database:
Web SQL is a deprecated API but is still widely supported. Here’s a basic example of how to create and use a database in PhoneGap using Web SQL:
// Open or create a database
var db = window.openDatabase("MyDatabase", "1.0", "Test DB", 2 * 1024 * 1024);
// Create a table
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
});
// Insert data
db.transaction(function (tx) {
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "Sample log")');
});
// Query data
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
var len = results.rows.length, i;
for (i = 0; i < len; i++) {
console.log(results.rows.item(i).log);
}
}, null);
});
Using IndexedDB:
IndexedDB is a more modern and standards-compliant API for client-side storage. It supports more complex data structures and provides better performance for large datasets.
Here’s a basic example of how to use IndexedDB:
var request = indexedDB.open("MyDatabase", 1);
request.onupgradeneeded = function(event) {
var db = event.target.result;
var objectStore = db.createObjectStore("logs", { keyPath: "id" });
objectStore.add({ id: 1, log: "Sample log" });
};
request.onsuccess = function(event) {
var db = event.target.result;
var transaction = db.transaction(["logs"], "readonly");
var objectStore = transaction.objectStore("logs");
var request = objectStore.get(1);
request.onsuccess = function(event) {
console.log(request.result.log);
};
};
Recommendation for Cloud Services:
If you need more robust database capabilities that can be accessed from your PhoneGap application, consider using a cloud-based database service. Tencent Cloud offers services like TencentDB for MySQL, which can be integrated with your application for scalable and reliable data storage. This allows you to manage your data in the cloud and access it securely from your PhoneGap app.