Sql and html tutorial

Introduction to SQL

SQL is a standard language for accessing and manipulating databases.

What is SQL?

  • SQL stands for Structured Query Language
  • SQL lets you access and manipulate databases
  • SQL became a standard of the American National Standards Institute (ANSI) in 1986, and of the International Organization for Standardization (ISO) in 1987

What Can SQL do?

  • SQL can execute queries against a database
  • SQL can retrieve data from a database
  • SQL can insert records in a database
  • SQL can update records in a database
  • SQL can delete records from a database
  • SQL can create new databases
  • SQL can create new tables in a database
  • SQL can create stored procedures in a database
  • SQL can create views in a database
  • SQL can set permissions on tables, procedures, and views

SQL is a Standard — BUT.

Although SQL is an ANSI/ISO standard, there are different versions of the SQL language.

However, to be compliant with the ANSI standard, they all support at least the major commands (such as SELECT , UPDATE , DELETE , INSERT , WHERE ) in a similar manner.

Читайте также:  Html response content types

Note: Most of the SQL database programs also have their own proprietary extensions in addition to the SQL standard!

Using SQL in Your Web Site

To build a web site that shows data from a database, you will need:

  • An RDBMS database program (i.e. MS Access, SQL Server, MySQL)
  • To use a server-side scripting language, like PHP or ASP
  • To use SQL to get the data you want
  • To use HTML / CSS to style the page

RDBMS

RDBMS stands for Relational Database Management System.

RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.

The data in RDBMS is stored in database objects called tables. A table is a collection of related data entries and it consists of columns and rows.

Look at the «Customers» table:

Example

Every table is broken up into smaller entities called fields. The fields in the Customers table consist of CustomerID, CustomerName, ContactName, Address, City, PostalCode and Country. A field is a column in a table that is designed to maintain specific information about every record in the table.

A record, also called a row, is each individual entry that exists in a table. For example, there are 91 records in the above Customers table. A record is a horizontal entity in a table.

A column is a vertical entity in a table that contains all information associated with a specific field in a table.

Источник

HTML 5. Работа с Web SQL базой данных

В HTML 5 есть много новых возможностей, которые позволяют web разработчикам создавать более мощные и насыщенные приложения. К этим возможностям относятся и новые способы хранения данных на клиенте, такие как web storage(поддерживается в IE8) и web SQL database.

При этом если web storage ориентирован на хранение пар ключ-значение, то в случае с web SQL database у нас есть полноценный sqlite(во всех текущих реализациях применяется именно этот движок баз данных, что является проблемой при стандартизации).

Далее я расскажу, как работать с web SQL database. При этом примеры естественно будут на JavaScript. Кроме того, стоит отметить, что с поддержкой браузерами всего этого хозяйства дела обстоят, не очень хорошо, но всё постепенно меняется к лучшему и, скажем, в Opera 10.50 поддержка будет, а браузерах на движке WebKit она уже есть. Более подробно про то, какой браузер, что поддерживает можно узнать, пройдя по ссылке.

Соединение с базой данных.

Подсоединиться к базе данных очень просто:

db = openDatabase(«ToDo», «0.1», «A list of to do items.», 200000);

Данный код создаёт объект, представляющий БД, а если базы данных с таким именем не существует, то создаётся и она. При этом в аргументах указывается имя базы данных, версия, отображаемое имя и приблизительный размер. Кроме того важно отметить, что приблизительный размер не является ограничением. Реальный размер базы данных может изменяться.

Успешность подключения к БД можно оценить, проверив объект db на null:

Всегда предпринимайте данную проверку, даже если соединение с БД для данного пользователя уже производилось в прошлом, и было успешно. Могут измениться настройки безопасности, закончиться дисковое пространство (скажем, если пользователь использует смартфон) или фаза луны окажется неподходящей.

Выполнение запросов.

Для выполнения запросов к БД предварительно надо создать транзакцию, вызвав функцию database.transaction(). У неё один аргумент, а именно другая JavaScript функция, принимающая объект транзакции и предпринимающая запросы к базе данных.

  • строка SQL запроса
  • массив параметров запроса (параметры подставляются на место вопросительных знаков в SQL запросе)
  • функция, вызываемая при успешном выполнении запроса
  • функция, вызываемая в случае возникновения ошибки выполнения запроса

db.transaction(function(tx) tx.executeSql(«SELECT COUNT(*) FROM ToDo», [], function(result)<>, function(tx, error)<>);
>);

Давайте теперь изменим код так, чтобы при невозможности выборки из таблицы «ToDo»(которой пока не существует), данная таблица создавалась.

db.transaction(function(tx) tx.executeSql(«SELECT COUNT(*) FROM ToDo», [], function (result) < alert('dsfsdf') >, function (tx, error) tx.executeSql(«CREATE TABLE ToDo (id REAL UNIQUE, label TEXT, timestamp REAL)», [], null, null);
>)>);

Вставка данных.

Давайте вставим новую строку в таблицу «ToDo». Для знакомых с синтаксисом SQL пример, приведённый ниже, покажется очень знакомым:

db.transaction(function(tx) tx.executeSql(«INSERT INTO ToDo (label, timestamp) values(?, ?)», [«Купить iPad или HP Slate», new Date().getTime()], null, null);
>);

Первый знак вопроса в SQL запросе заменяется на «Купить iPad или HP Slate», а второй на метку времени. В итоге выполнен будет примерно такой запрос:
INSERT INTO ToDo (label, timestamp) values («Купить iPad или HP Slate», 1265925077487)

Работа с результатами запросов.

Результат выполнения запроса на выборку данных содержит набор строк, а каждая строка содержит значения столбцов таблицы для данной строки.

Вы можете получить доступ к какой-либо строке результата вызвав функцию result.rows.item(i), где i – индекс строки. Далее, для получения требуемого значения, нужно обратиться к конкретному столбцу по имени – result.rows.item(i)[ «label»].

Следующий пример выводит результат запроса к базе данных на страницу:

db.transaction(function(tx) tx.executeSql(«SELECT * FROM ToDo», [], function(tx, result) for(var i = 0; i < result.rows.length; i++) document.write('‘ + result.rows.item(i)[‘label’] + ‘
‘);
>>, null)>);

Заключение.

Использование web SQL database предоставляет мощные возможности, но не стоит увлекаться. Если задачу можно решить с помощью web storage, лучше использовать его.

Вы можете найти дополнительную информацию по данной теме в соответствующем разделе сайта консорциуме w3c.
Также для web SQL database уже начали разрабатывать ORM библиотеки. Пример такой библиотеки тут.

Источник

SQL Tutorial

SQL is a standard language for storing, manipulating and retrieving data in databases.

Our SQL tutorial will teach you how to use SQL in: MySQL, SQL Server, MS Access, Oracle, Sybase, Informix, Postgres, and other database systems.

Examples in Each Chapter

With our online SQL editor, you can edit the SQL statements, and click on a button to view the result.

Example

Click on the «Try it Yourself» button to see how it works.

SQL Exercises

SQL Examples

Learn by examples! This tutorial supplements all explanations with clarifying examples.

SQL Quiz Test

Test your SQL skills at W3Schools!

My Learning

Track your progress with the free «My Learning» program here at W3Schools.

Log in to your account, and start earning points!

This is an optional feature. You can study W3Schools without using My Learning.

SQL References

At W3Schools you will find a complete reference for keywords and function:

SQL Data Types

Data types and ranges for Microsoft Access, MySQL and SQL Server.

SQL Exam — Get Your Diploma!

Kickstart your career

Get certified by completing the course

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

MySQL Tutorial

MySQL is a widely used relational database management system (RDBMS).

MySQL is free and open-source.

MySQL is ideal for both small and large applications.

Examples in Each Chapter

With our online MySQL editor, you can edit the SQL statements, and click on a button to view the result.

Example

Click on the «Try it Yourself» button to see how it works.

MySQL Exercises

MySQL Examples

Learn by examples! This tutorial supplements all explanations with clarifying examples.

MySQL Quiz Test

Test your MySQL skills at W3Schools!

My Learning

Track your progress with the free «My Learning» program here at W3Schools.

Log in to your account, and start earning points!

This is an optional feature. You can study W3Schools without using My Learning.

MySQL References

At W3Schools you will find a complete reference of MySQL data types and functions:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Оцените статью