Front-end Tutorials

Front-end Tutorials

HTMLCSSSassJavaScriptReactJS
CMS Tutorials

CMS Tutorials

WordPress
Tutorials expand

HTML Web SQL

Posted in HTML Tutorial
Updated on Sep 03, 2024
By Mari Selvan
πŸ‘οΈ 149 - Views
⏳ 4 mins
πŸ’¬ 1 Comment
HTML Web SQL

Photo Credit to CodeToFun

πŸ™‹ Introduction

Web SQL Database is a deprecated web standard for storing data in a structured manner using a SQL-based relational database. While it's no longer recommended for new projects, understanding Web SQL can be valuable for maintaining legacy applications or working with older browser environments that still support this technology.

❓ What Is Web SQL?

Web SQL is a database API that allows web applications to store data using a relational database model. It uses SQL (Structured Query Language) for accessing and manipulating the data, making it familiar to developers who have experience with traditional relational databases like MySQL or SQLite.

πŸ›‘ Why Web SQL Was Deprecated

Web SQL was deprecated because it lacked a standardized implementation across different browsers, leading to inconsistencies. The W3C decided not to pursue Web SQL as an official standard, favoring IndexedDB as the more robust and future-proof solution for client-side storage.

🧠 Basic Concepts

  • Database: A structured collection of data organized in tables.
  • Table: A set of data elements organized in rows and columns.
  • SQL: A language for managing and querying relational databases.
  • Transaction: A sequence of operations performed as a single unit, ensuring data consistency.

πŸ—„οΈ Creating a Database

To create a Web SQL database, you use the openDatabase method. This method opens an existing database or creates a new one if it doesn't exist.

javascript
Copied
Copy To Clipboard
const db = openDatabase('myDatabase', '1.0', 'Test DB', 2 * 1024 * 1024);

db.transaction(function(tx) {
  tx.executeSql('CREATE TABLE IF NOT EXISTS myTable (id unique, name)');
});

πŸ’» Executing SQL Queries

You can execute SQL queries using the executeSql method within a transaction. This allows you to create tables, insert data, update records, and more<./p>

javascript
Copied
Copy To Clipboard
db.transaction(function(tx) {
  tx.executeSql('INSERT INTO myTable (id, name) VALUES (1, "John Doe")');
});

πŸ’° Transactions and Error Handling

Web SQL operations are wrapped in transactions, which ensure that a series of queries are executed as a single unit. If any part of the transaction fails, the entire transaction is rolled back, maintaining data integrity.

javascript
Copied
Copy To Clipboard
db.transaction(function(tx) {
  tx.executeSql('UPDATE myTable SET name = "Jane Doe" WHERE id = 1');
}, function(error) {
  console.error('Transaction error:', error.message);
}, function() {
  console.log('Transaction successful');
});

πŸ‘¨β€πŸŽ¨ Working with Results

When you execute a query that returns data (like SELECT), you can handle the results using a callback function. The results are provided as a ResultSet object.

javascript
Copied
Copy To Clipboard
db.transaction(function(tx) {
  tx.executeSql('SELECT * FROM myTable', [], function(tx, results) {
    const len = results.rows.length;
    for (let i = 0; i < len; i++) {
      console.log('Record:', results.rows.item(i));
    }
  });
});

πŸ† Best Practices

  • Use IndexedDB for New Projects: Since Web SQL is deprecated, prefer IndexedDB for new projects.
  • Error Handling: Implement robust error handling to manage any issues that arise during transactions.
  • Data Persistence: Be cautious with the amount of data stored, as Web SQL is intended for lightweight client-side storage.
  • πŸ“ Example

    Here’s a complete example demonstrating the creation of a database, adding a record, and retrieving all records:

    HTML
    Copied
    Copy To Clipboard
    <!DOCTYPE html>
    <html>
    <head>
      <title>Web SQL Example</title>
    </head>
    <body>
      <h1>Web SQL Example</h1>
      <button id="add">Add Record</button>
      <button id="get">Get All Records</button>
    
      <script>
        const db = openDatabase('myDatabase', '1.0', 'Test DB', 2 * 1024 * 1024);
    
        db.transaction(function(tx) {
          tx.executeSql('CREATE TABLE IF NOT EXISTS myTable (id unique, name)');
        });
    
        document.getElementById('add').addEventListener('click', () => {
          db.transaction(function(tx) {
            tx.executeSql('INSERT INTO myTable (id, name) VALUES (1, "John Doe")');
          });
        });
    
        document.getElementById('get').addEventListener('click', () => {
          db.transaction(function(tx) {
            tx.executeSql('SELECT * FROM myTable', [], function(tx, results) {
              const len = results.rows.length;
              for (let i = 0; i < len; i++) {
                console.log('Record:', results.rows.item(i));
              }
            });
          });
        });
      </script>
    </body>
    </html>

    πŸŽ‰ Conclusion

    While HTML Web SQL is no longer recommended for new projects due to its deprecation, it remains a useful tool for maintaining legacy applications. Understanding how Web SQL works can help you manage and update older projects effectively, but for modern web development, IndexedDB is the preferred choice for client-side storage.

πŸ‘¨β€πŸ’» Join our Community:

To get interesting news and instant updates on Front-End, Back-End, CMS and other Frameworks. Please Join the Telegram Channel:

Author

author
πŸ‘‹ Hey, I'm Mari Selvan

For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.

Buy me a coffee to make codetofun.com free for everyone.

Buy me a Coffee

Share Your Findings to All

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
We make use of cookies to improve our user experience. By using this website, you agree with our Cookies Policy
AgreeCookie Policy