This document provides an overview and outline of a 12-lesson MariaDB training course. The lessons cover topics such as MariaDB installation and configuration, database and user administration, data manipulation, indexes, transactions, backups and replication. Each lesson includes brief descriptions of the concepts and tasks that will be covered.
This document provides a cheat sheet for MySQL with summaries of basic operations, table operations, storage engines, transaction operations, administration operations, and more. It includes commands for connecting to MySQL, starting and stopping the MySQL daemon, checking server status, creating and modifying databases and tables, importing and exporting data, and server administration tasks like backups, restores, and log maintenance. A link is provided to the original Japanese sheet as well as the MySQL official documentation.
1) The document provides instructions for installing Pentaho on CentOS, including creating a user and group, installing Java, MySQL, and Pentaho.
2) MySQL is installed using a YUM repository, then configured and secured.
3) Pentaho is extracted and MySQL databases are initialized with SQL scripts to integrate Pentaho and MySQL.
1) The document discusses different methods for backing up an Oracle database, including using RMAN from the command line or Enterprise Manager GUI, and configuring the backup environment.
2) It provides step-by-step instructions for backing up an Oracle database that is in ARCHIVELOG or NOARCHIVELOG mode using RMAN, either via the CLI or the EM GUI.
3) The document also covers using Oracle's Flashback feature to enable point-in-time recovery of the database if unwanted changes are made, and provides steps for enabling Flashback via SQL*Plus or the EM.
The document discusses MySQL database backup and restore operations. It provides examples of standard and functional backup commands using mysqldump that can backup an entire database, specific tables, or all databases. It also lists various mysqldump options that can be used to customize backups, such as adding DROP statements, locking tables, skipping triggers or table creation information. Maintaining regular database backups is important for data protection and recovery.
soft-shake.ch - JBoss AS 7, la révolutionsoft-shake.ch
Alexis Hassler
JBoss AS 7 est sorti pendant l’été 2011. Cette version est une véritable révolution pour tous les utilisateurs JBoss : temps de démarrage et de déploiement record, techniques d’administration renouvelées, configuration simplifiée et plus expressive,…
Dans cette présentation, j’explique ces nouveautés et je les montre avec des vrais morceaux de ligne de commande.
http://soft-shake.ch/2011/conference/sessions/java/2011/09/13/jboss.html
This document provides an overview of Hibernate and how to implement basic object-relational mapping with Hibernate in a Spring and Maven project connected to a MySQL database. It discusses adding Hibernate and database dependencies to Maven, configuring Hibernate, and examples of basic CRUD operations and association mappings like one-to-one relationships. Key topics include setting up Hibernate configuration files, annotating entities with JPA annotations, and performing save, update, and delete operations through the Hibernate session factory.
The document provides information about MySQL storage engines:
- It describes the main storage engines like MyISAM, InnoDB, Memory, Archive, etc and their key features.
- It explains how to specify a storage engine when creating a table, check the engine of an existing table, and convert a table to use a different engine.
- It also gives details on important InnoDB related parameters like innodb_file_per_table and how to check if InnoDB is enabled on a MySQL server.
This document provides a cheat sheet for MySQL with summaries of basic operations, table operations, storage engines, transaction operations, administration operations, and more. It includes commands for connecting to MySQL, starting and stopping the MySQL daemon, checking server status, creating and modifying databases and tables, importing and exporting data, and server administration tasks like backups, restores, and log maintenance. A link is provided to the original Japanese sheet as well as the MySQL official documentation.
1) The document provides instructions for installing Pentaho on CentOS, including creating a user and group, installing Java, MySQL, and Pentaho.
2) MySQL is installed using a YUM repository, then configured and secured.
3) Pentaho is extracted and MySQL databases are initialized with SQL scripts to integrate Pentaho and MySQL.
1) The document discusses different methods for backing up an Oracle database, including using RMAN from the command line or Enterprise Manager GUI, and configuring the backup environment.
2) It provides step-by-step instructions for backing up an Oracle database that is in ARCHIVELOG or NOARCHIVELOG mode using RMAN, either via the CLI or the EM GUI.
3) The document also covers using Oracle's Flashback feature to enable point-in-time recovery of the database if unwanted changes are made, and provides steps for enabling Flashback via SQL*Plus or the EM.
The document discusses MySQL database backup and restore operations. It provides examples of standard and functional backup commands using mysqldump that can backup an entire database, specific tables, or all databases. It also lists various mysqldump options that can be used to customize backups, such as adding DROP statements, locking tables, skipping triggers or table creation information. Maintaining regular database backups is important for data protection and recovery.
soft-shake.ch - JBoss AS 7, la révolutionsoft-shake.ch
Alexis Hassler
JBoss AS 7 est sorti pendant l’été 2011. Cette version est une véritable révolution pour tous les utilisateurs JBoss : temps de démarrage et de déploiement record, techniques d’administration renouvelées, configuration simplifiée et plus expressive,…
Dans cette présentation, j’explique ces nouveautés et je les montre avec des vrais morceaux de ligne de commande.
http://soft-shake.ch/2011/conference/sessions/java/2011/09/13/jboss.html
This document provides an overview of Hibernate and how to implement basic object-relational mapping with Hibernate in a Spring and Maven project connected to a MySQL database. It discusses adding Hibernate and database dependencies to Maven, configuring Hibernate, and examples of basic CRUD operations and association mappings like one-to-one relationships. Key topics include setting up Hibernate configuration files, annotating entities with JPA annotations, and performing save, update, and delete operations through the Hibernate session factory.
The document provides information about MySQL storage engines:
- It describes the main storage engines like MyISAM, InnoDB, Memory, Archive, etc and their key features.
- It explains how to specify a storage engine when creating a table, check the engine of an existing table, and convert a table to use a different engine.
- It also gives details on important InnoDB related parameters like innodb_file_per_table and how to check if InnoDB is enabled on a MySQL server.
1. The document discusses various SQL concepts including DCL (Data Control Language), DDL (Data Definition Language), DML (Data Manipulation Language), functions, users, phpMyAdmin, and procedures.
2. Key SQL commands covered include COMMIT, ROLLBACK, GRANT, REVOKE, CREATE, ALTER, DROP, SELECT, INSERT, UPDATE, DELETE.
3. The document also discusses creating, using, and dropping MySQL users, as well as the features and uses of phpMyAdmin for database administration.
This document provides steps to install and configure MySQL 5.1 on CentOS 6.4. It describes downloading required libraries, editing the configuration file to set the character set to UTF-8, starting the MySQL service, securing the root user and removing test databases. It also demonstrates creating a database and table, loading, querying, updating and backing up data.
The document provides a tutorial on using SQL commands in MySQL. It begins with an overview of common commands like CREATE DATABASE, DROP DATABASE, CREATE TABLE, INSERT INTO. Sections then cover topics like relationships between tables, backups and indexing. The document includes examples to create a sample "southwind" database with a "products" table, insert rows, and run queries. It explains column definitions and provides the SQL needed to generate the tables and insert sample data.
This document provides configuration steps and commands for demonstrating RMAN backup and recovery functionality in Oracle Database including: configuring RMAN, performing full and incremental backups, monitoring backups, checking the fast recovery area (FRA), creating an RMAN catalog, and demonstrating restore and recovery operations. It also covers advanced RMAN topics like tablespace point-in-time recovery, backup optimization settings, and troubleshooting.
This document provides instructions for enabling the EPEL (Extra Packages for Enterprise Linux) repository on RHEL (Red Hat Enterprise Linux) systems to gain access to additional packages. It describes downloading the EPEL rpm package, installing it to enable the repository, and checking that it is functioning properly by viewing available packages and installing a library from EPEL.
Ajuste (tuning) del rendimiento de SQL Server 2008Eduardo Castro
En el siguiente webcast http://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032438450&Culture=es-AR analizamos las herramientas de desempeño de SQL Server 2008 y cómo utilizarlas.
Saludos,
Ing. Eduardo Castro Martínez, PhD – Microsoft SQL Server MVP
http://mswindowscr.org
http://comunidadwindows.org
Costa Rica
Technorati Tags: SQL Server
LiveJournal Tags: SQL Server
del.icio.us Tags: SQL Server
http://ecastrom.blogspot.com
http://ecastrom.wordpress.com
http://ecastrom.spaces.live.com
http://universosql.blogspot.com
http://todosobresql.blogspot.com
http://todosobresqlserver.wordpress.com
http://mswindowscr.org/blogs/sql/default.aspx
http://citicr.org/blogs/noticias/default.aspx
http://sqlserverpedia.blogspot.com/
This document provides an overview and agenda for a presentation on MySQL best practices for DBAs and developers. The presentation covers essential MySQL configuration practices like server SQL mode and storage engines. It also discusses improving SQL, user security, schema optimizations, instrumentation, and monitoring. Specific topics include comment SQL, formatting SQL, future proofing SQL, and analyzing SQL. The document provides examples and recommendations for each topic.
This document provides instructions for installing and configuring Cacoo Enterprise. It outlines the system requirements, installation steps including creating databases and tables, placing files, and optional configuration changes. The key steps are:
1. Install required software like Java, Tomcat, PostgreSQL, and image/PDF tools.
2. Create the cacoo database and tables using the provided SQL files.
3. Place the cacoo.war file in the Tomcat webapps directory.
4. Optionally change database, mail, and other settings in configuration files.
Coding For Config: Install Profile Development Using FeaturesMyplanet Digital
This document provides an overview of how to create an install profile in Drupal. It discusses the key files and folders needed, including .info, .profile, .install files to define the profile. It also covers make files needed to build the profile and dependencies, as well as example code for common tasks in install hooks like enabling modules, setting variables, populating menus and vocabularies.
SMON is an Oracle background process that performs various system monitoring and cleanup tasks. It cleans up temporary segments in tablespaces, merges free extents to reduce fragmentation, and removes unused entries from the OBJ$ data dictionary table. SMON runs cleanup operations after instance startup and periodically over time to manage system resources and optimize performance.
Installing oracle grid infrastructure and database 12c r1Voeurng Sovann
This document provides instructions for installing Oracle Grid Infrastructure and Oracle Database 12c R1 on a standalone Linux server. It describes how to:
1. Configure the server with required packages, users, groups, and directories for the Oracle software.
2. Install Oracle Grid Infrastructure 12c R1 using the Oracle Universal Installer and configure an ASM disk group and instance.
3. Install Oracle Database 12c R1 software, and use DBCA to create a database called "asmdb" that uses the ASM disk groups for storage and is accessible by the listener called "LISTENER_ASM".
This document provides summaries of commands and configuration files for system administration tasks in Debian GNU/Linux. It covers topics such as system configuration files in /etc/, managing services and daemons, installing and managing packages with APT, managing packages with dpkg, configuring the network, setting up a web server and database, and getting help.
This document provides an overview of Database Jones, a Node.js API for highly scalable database access to MySQL Cluster. It introduces J.D. Duncan and Craig Russell, the creators of Database Jones, and describes how Database Jones provides an asynchronous JavaScript API that can be used with MySQL Cluster and other databases. It also summarizes the key features and capabilities of Database Jones, including its data modeling approaches, operations, and usage with Node.js applications.
This document describes 10 steps to achieve a 10x performance improvement for a MySQL database for a social media website. The steps include monitoring the database, identifying slow SQL queries, analyzing problem queries, improving indexes, offloading read load to slaves, improving SQL, using optimal storage engines, and implementing caching. Key actions include installing monitoring tools, using mk-query-digest to analyze SQL, adding indexes, configuring InnoDB, converting tables to InnoDB, and caching query results and content with Memcache. The goal is to optimize the database infrastructure and queries to handle the load of a growing web 2.0 application.
The document discusses building a custom Linux kernel from source. It describes downloading kernel source code for Fedora or RHEL, installing dependencies and prepping the source code. It explains how to replace an existing custom kernel configuration, use make oldconfig to carry over existing options, and customize the kernel using make menuconfig, make gconfig or make config. Building the kernel produces files in directories under ~/rpmbuild after compiling.
The user created a database called db_latihan_uts using MySQL. They then created a table called tb_user within that database to store user data, including a primary key field and fields for name, gender, address, and phone number. The user inserted a sample record into the tb_user table and verified it was added by selecting all records from the table.
in LATVIAN language: Viens no galvenajiem datubāzes administratora uzdevumiem ir veikt datubāzes backup un prast no tā atjaunot datubāzi. Mysql bezmaksas versija nepiedāvā datubāzes administratoram ļoti daudz izvēles. Sava prezentācija es pastāstīšu par šādiem rīkiem:
-- MySQLdump
-- Percona XtraBackup
-- Mysql enterprise backup (MEB)
--Un citiem rīkiem kas palīdz man veikt db backup
MySQL replication allows data from a master database server to be copied to one or more slave database servers. It provides advantages like improving performance through load balancing, increasing data security with backups on slaves, and enabling analytics on slaves without impacting the master. Basic replication involves setting up a master server and slave server with unique IDs, configuring the master to log binary changes, and pointing the slave to the master so it can copy the binary log entries.
This document provides an introduction to relational database management systems (RDBMS) through a series of slides. It covers topics such as installing MySQL, connecting to databases, using SQL commands to retrieve and manipulate data, and designing databases. The slides introduce fundamental RDBMS concepts like tables, rows, columns, keys, and relationships. It also demonstrates how to use the MySQL command line interface to issue queries and explore database structure. Examples are provided for common SQL statements like SELECT, CREATE, INSERT and more.
1. The document discusses various SQL concepts including DCL (Data Control Language), DDL (Data Definition Language), DML (Data Manipulation Language), functions, users, phpMyAdmin, and procedures.
2. Key SQL commands covered include COMMIT, ROLLBACK, GRANT, REVOKE, CREATE, ALTER, DROP, SELECT, INSERT, UPDATE, DELETE.
3. The document also discusses creating, using, and dropping MySQL users, as well as the features and uses of phpMyAdmin for database administration.
This document provides steps to install and configure MySQL 5.1 on CentOS 6.4. It describes downloading required libraries, editing the configuration file to set the character set to UTF-8, starting the MySQL service, securing the root user and removing test databases. It also demonstrates creating a database and table, loading, querying, updating and backing up data.
The document provides a tutorial on using SQL commands in MySQL. It begins with an overview of common commands like CREATE DATABASE, DROP DATABASE, CREATE TABLE, INSERT INTO. Sections then cover topics like relationships between tables, backups and indexing. The document includes examples to create a sample "southwind" database with a "products" table, insert rows, and run queries. It explains column definitions and provides the SQL needed to generate the tables and insert sample data.
This document provides configuration steps and commands for demonstrating RMAN backup and recovery functionality in Oracle Database including: configuring RMAN, performing full and incremental backups, monitoring backups, checking the fast recovery area (FRA), creating an RMAN catalog, and demonstrating restore and recovery operations. It also covers advanced RMAN topics like tablespace point-in-time recovery, backup optimization settings, and troubleshooting.
This document provides instructions for enabling the EPEL (Extra Packages for Enterprise Linux) repository on RHEL (Red Hat Enterprise Linux) systems to gain access to additional packages. It describes downloading the EPEL rpm package, installing it to enable the repository, and checking that it is functioning properly by viewing available packages and installing a library from EPEL.
Ajuste (tuning) del rendimiento de SQL Server 2008Eduardo Castro
En el siguiente webcast http://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032438450&Culture=es-AR analizamos las herramientas de desempeño de SQL Server 2008 y cómo utilizarlas.
Saludos,
Ing. Eduardo Castro Martínez, PhD – Microsoft SQL Server MVP
http://mswindowscr.org
http://comunidadwindows.org
Costa Rica
Technorati Tags: SQL Server
LiveJournal Tags: SQL Server
del.icio.us Tags: SQL Server
http://ecastrom.blogspot.com
http://ecastrom.wordpress.com
http://ecastrom.spaces.live.com
http://universosql.blogspot.com
http://todosobresql.blogspot.com
http://todosobresqlserver.wordpress.com
http://mswindowscr.org/blogs/sql/default.aspx
http://citicr.org/blogs/noticias/default.aspx
http://sqlserverpedia.blogspot.com/
This document provides an overview and agenda for a presentation on MySQL best practices for DBAs and developers. The presentation covers essential MySQL configuration practices like server SQL mode and storage engines. It also discusses improving SQL, user security, schema optimizations, instrumentation, and monitoring. Specific topics include comment SQL, formatting SQL, future proofing SQL, and analyzing SQL. The document provides examples and recommendations for each topic.
This document provides instructions for installing and configuring Cacoo Enterprise. It outlines the system requirements, installation steps including creating databases and tables, placing files, and optional configuration changes. The key steps are:
1. Install required software like Java, Tomcat, PostgreSQL, and image/PDF tools.
2. Create the cacoo database and tables using the provided SQL files.
3. Place the cacoo.war file in the Tomcat webapps directory.
4. Optionally change database, mail, and other settings in configuration files.
Coding For Config: Install Profile Development Using FeaturesMyplanet Digital
This document provides an overview of how to create an install profile in Drupal. It discusses the key files and folders needed, including .info, .profile, .install files to define the profile. It also covers make files needed to build the profile and dependencies, as well as example code for common tasks in install hooks like enabling modules, setting variables, populating menus and vocabularies.
SMON is an Oracle background process that performs various system monitoring and cleanup tasks. It cleans up temporary segments in tablespaces, merges free extents to reduce fragmentation, and removes unused entries from the OBJ$ data dictionary table. SMON runs cleanup operations after instance startup and periodically over time to manage system resources and optimize performance.
Installing oracle grid infrastructure and database 12c r1Voeurng Sovann
This document provides instructions for installing Oracle Grid Infrastructure and Oracle Database 12c R1 on a standalone Linux server. It describes how to:
1. Configure the server with required packages, users, groups, and directories for the Oracle software.
2. Install Oracle Grid Infrastructure 12c R1 using the Oracle Universal Installer and configure an ASM disk group and instance.
3. Install Oracle Database 12c R1 software, and use DBCA to create a database called "asmdb" that uses the ASM disk groups for storage and is accessible by the listener called "LISTENER_ASM".
This document provides summaries of commands and configuration files for system administration tasks in Debian GNU/Linux. It covers topics such as system configuration files in /etc/, managing services and daemons, installing and managing packages with APT, managing packages with dpkg, configuring the network, setting up a web server and database, and getting help.
This document provides an overview of Database Jones, a Node.js API for highly scalable database access to MySQL Cluster. It introduces J.D. Duncan and Craig Russell, the creators of Database Jones, and describes how Database Jones provides an asynchronous JavaScript API that can be used with MySQL Cluster and other databases. It also summarizes the key features and capabilities of Database Jones, including its data modeling approaches, operations, and usage with Node.js applications.
This document describes 10 steps to achieve a 10x performance improvement for a MySQL database for a social media website. The steps include monitoring the database, identifying slow SQL queries, analyzing problem queries, improving indexes, offloading read load to slaves, improving SQL, using optimal storage engines, and implementing caching. Key actions include installing monitoring tools, using mk-query-digest to analyze SQL, adding indexes, configuring InnoDB, converting tables to InnoDB, and caching query results and content with Memcache. The goal is to optimize the database infrastructure and queries to handle the load of a growing web 2.0 application.
The document discusses building a custom Linux kernel from source. It describes downloading kernel source code for Fedora or RHEL, installing dependencies and prepping the source code. It explains how to replace an existing custom kernel configuration, use make oldconfig to carry over existing options, and customize the kernel using make menuconfig, make gconfig or make config. Building the kernel produces files in directories under ~/rpmbuild after compiling.
The user created a database called db_latihan_uts using MySQL. They then created a table called tb_user within that database to store user data, including a primary key field and fields for name, gender, address, and phone number. The user inserted a sample record into the tb_user table and verified it was added by selecting all records from the table.
in LATVIAN language: Viens no galvenajiem datubāzes administratora uzdevumiem ir veikt datubāzes backup un prast no tā atjaunot datubāzi. Mysql bezmaksas versija nepiedāvā datubāzes administratoram ļoti daudz izvēles. Sava prezentācija es pastāstīšu par šādiem rīkiem:
-- MySQLdump
-- Percona XtraBackup
-- Mysql enterprise backup (MEB)
--Un citiem rīkiem kas palīdz man veikt db backup
MySQL replication allows data from a master database server to be copied to one or more slave database servers. It provides advantages like improving performance through load balancing, increasing data security with backups on slaves, and enabling analytics on slaves without impacting the master. Basic replication involves setting up a master server and slave server with unique IDs, configuring the master to log binary changes, and pointing the slave to the master so it can copy the binary log entries.
This document provides an introduction to relational database management systems (RDBMS) through a series of slides. It covers topics such as installing MySQL, connecting to databases, using SQL commands to retrieve and manipulate data, and designing databases. The slides introduce fundamental RDBMS concepts like tables, rows, columns, keys, and relationships. It also demonstrates how to use the MySQL command line interface to issue queries and explore database structure. Examples are provided for common SQL statements like SELECT, CREATE, INSERT and more.
MySQL is a widely used open-source relational database management system. The presentation covered how to install, configure, start, stop, and connect to MySQL. It also discussed how to load and view data, backup databases, set up user authentication, and where to go for additional training resources. Common MySQL commands and tools were demonstrated.
OSMC 2008 | Monitoring MySQL by Geert VanderkelenNETWAYS
Monitoring MySQL has a long history within Nagios. Several plugins are available already. In addition to that, there are probably lots of plugins that have been developed by the community. We take a look at some of these and discuss what kind of additional useful information could be pulled out of a MySQL Server for monitoring it even better. A simple example on how to write such plugins will be shown, also using NDB API for monitoring MySQL Cluster. Now that MySQL Enterprise Monitor (MEM) is available, we'll go through the possibilities for combining the two platforms. We will also discuss the NDOUtils for storing configuration and event data using MySQL.
This talk starts with a brief overview of MySQL itself: some history, where it's heading too, and why it is so successful.
This document provides instructions for setting up a TrinityCore private server on Linux. It discusses downloading and compiling TrinityCore source code, configuring the required MySQL databases, and basic server configuration. Key steps include installing prerequisites like build tools and libraries, cloning the TrinityCore source repository, running cmake to configure the build, importing SQL files to set up the auth, characters, and world databases, and editing the realmlist table to point clients to the server.
MySQL is a relational database management system that was created to be fast, reliable, and easy to use. It supports multiple platforms and can be downloaded and installed for free. Basic commands for MySQL include CREATE, SELECT, DELETE, INSERT, UPDATE, and DROP to manage tables and data.
This document provides an introduction to relational database management systems (RDBMS) through a series of slides. It covers topics such as installing MySQL, connecting to databases using SQL, database design with MySQL Workbench, and using biological databases with RDBMS. Instructions are provided for installing MySQL on Linux, Windows, and Mac operating systems. The key components of RDBMS and SQL are defined, including creating databases and tables, retrieving and sorting data.
Memcached Functions For My Sql Seemless Caching In My SqlMySQLConference
The document summarizes memcached Functions for MySQL, which are user defined functions (UDFs) that allow MySQL to interact with the memcached caching server. The UDFs provide functions to store, retrieve, delete data from memcached as well as retrieve server stats and configure client behaviors. The UDFs are written in C using the libmemcached client library and MySQL UDF API. They allow caching data from MySQL queries in memcached and combining data from MySQL tables and memcached in queries.
MariaDB is the default MySQL database installed on Red Hat Enterprise Linux 7. It is installed by running commands like "yum install mariadb" and then secured by running "mysql_secure_installation" to set the root password. Once installed and secured, databases and users can be created and the connection can be tested.
Introduction to MariaDB. Covers the history of Structured Query language, MySQL and MariaDB, shows how to install on Windows, Mac or Linux desktop, and practical examples.
Running and Shutting down MySQL Server:
- Check if MySQL server is running using 'ps -ef | grep mysqld' command. Start server using './safe_mysqld &' if not running.
- Shut down running server using './mysqladmin -u root -p shutdown' command.
Setting Up a MySQL User Account:
- Add new user to 'user' table in 'mysql' database using INSERT query, encrypting password.
- Use FLUSH PRIVILEGES to reload grant tables and allow connection with new user.
- Can also use GRANT SQL command to add user for a specific database.
The /etc/my.cnf File
Watch Re-runs on your SQL Server with RML Utilitiesdpcobb
RML Utilities provide command line tools and interactive reports enabling you to:
Take SQL trace files (captured with SQL Profiler, sp_trace or extended events in SQL 2012+),
Process them into replayable RML files (using readtrace.exe),
Play them back in a different SQL environment (using ostress.exe),
And compare the performance at a granular level (using reporter.exe or custom queries).
The document provides a rollout and backout plan for installing SQL Server 2000 on a standalone server. The summary is:
1. The rollout plan details the pre-installation checks, uninstalling the existing SQL Server, reinstalling SQL Server, post-installation checks, and disaster recovery steps.
2. The backout plan only briefly mentions pre-installation checks as the focus is on the rollout plan.
3. Key steps in the rollout plan include detaching databases, uninstalling SQL Server, running the installation, configuring services, and attaching databases post-installation.
4. Disaster recovery steps cover rebuilding the master database if it becomes corrupted, which requires using files from the installation media
The document provides an overview of installing Oracle 10g R2 database on Unbreakable Linux. It discusses Linux file system structure, installing Oracle software, configuring the network and kernel parameters, creating users and groups, and post-installation steps like starting the listener, database, and Enterprise Manager. Key tasks covered include checking system requirements, running the Oracle installer, configuring environment variables, and accessing the database using SQL*Plus and Enterprise Manager.
SQL Server is a relational database management system developed by Microsoft that supports the SQL language. It has various editions like Enterprise, Standard, and Web. SQL Server allows running multiple instances of the same version on a single machine for benefits like installation of different versions, maintenance of environments, and reducing temporary problems. Key features include creating, altering, and dropping databases and tables. Data can be manipulated using insert, update, and delete commands. Primary keys, foreign keys, unique constraints, and indexes can be defined to enforce data integrity and improve query performance.
This document provides information about installing and using the Firebird RDBMS, including:
- The two main types of Firebird servers and how to start/stop the Superserver.
- Default username and password for administration, and how to add/modify user accounts.
- Using the isql tool to connect to databases and execute SQL statements.
- Basic troubleshooting for common errors.
- Security measures like logging login attempts and restricting access after failed logins.
- Using the GBAK tool to backup and restore entire Firebird databases.
This document outlines an introduction to relational database management systems (RDBMS). It discusses installing MySQL, connecting to databases using the MySQL monitor, and provides an overview of basic SQL commands. The topics covered include creating databases and users, granting privileges, and executing SQL statements to define tables and populate them with data.
This document outlines an introduction to relational database management systems (RDBMS). It discusses installing MySQL, connecting to databases using the MySQL monitor, and provides an overview of basic SQL commands. The topics covered include creating databases and users, granting privileges, and executing SQL statements to define tables and populate them with data.
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdfflufftailshop
When it comes to unit testing in the .NET ecosystem, developers have a wide range of options available. Among the most popular choices are NUnit, XUnit, and MSTest. These unit testing frameworks provide essential tools and features to help ensure the quality and reliability of code. However, understanding the differences between these frameworks is crucial for selecting the most suitable one for your projects.
This presentation provides valuable insights into effective cost-saving techniques on AWS. Learn how to optimize your AWS resources by rightsizing, increasing elasticity, picking the right storage class, and choosing the best pricing model. Additionally, discover essential governance mechanisms to ensure continuous cost efficiency. Whether you are new to AWS or an experienced user, this presentation provides clear and practical tips to help you reduce your cloud costs and get the most out of your budget.
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...Tatiana Kojar
Skybuffer AI, built on the robust SAP Business Technology Platform (SAP BTP), is the latest and most advanced version of our AI development, reaffirming our commitment to delivering top-tier AI solutions. Skybuffer AI harnesses all the innovative capabilities of the SAP BTP in the AI domain, from Conversational AI to cutting-edge Generative AI and Retrieval-Augmented Generation (RAG). It also helps SAP customers safeguard their investments into SAP Conversational AI and ensure a seamless, one-click transition to SAP Business AI.
With Skybuffer AI, various AI models can be integrated into a single communication channel such as Microsoft Teams. This integration empowers business users with insights drawn from SAP backend systems, enterprise documents, and the expansive knowledge of Generative AI. And the best part of it is that it is all managed through our intuitive no-code Action Server interface, requiring no extensive coding knowledge and making the advanced AI accessible to more users.
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfMalak Abu Hammad
Discover how MongoDB Atlas and vector search technology can revolutionize your application's search capabilities. This comprehensive presentation covers:
* What is Vector Search?
* Importance and benefits of vector search
* Practical use cases across various industries
* Step-by-step implementation guide
* Live demos with code snippets
* Enhancing LLM capabilities with vector search
* Best practices and optimization strategies
Perfect for developers, AI enthusiasts, and tech leaders. Learn how to leverage MongoDB Atlas to deliver highly relevant, context-aware search results, transforming your data retrieval process. Stay ahead in tech innovation and maximize the potential of your applications.
#MongoDB #VectorSearch #AI #SemanticSearch #TechInnovation #DataScience #LLM #MachineLearning #SearchTechnology
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slackshyamraj55
Discover the seamless integration of RPA (Robotic Process Automation), COMPOSER, and APM with AWS IDP enhanced with Slack notifications. Explore how these technologies converge to streamline workflows, optimize performance, and ensure secure access, all while leveraging the power of AWS IDP and real-time communication via Slack notifications.
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc
How does your privacy program stack up against your peers? What challenges are privacy teams tackling and prioritizing in 2024?
In the fifth annual Global Privacy Benchmarks Survey, we asked over 1,800 global privacy professionals and business executives to share their perspectives on the current state of privacy inside and outside of their organizations. This year’s report focused on emerging areas of importance for privacy and compliance professionals, including considerations and implications of Artificial Intelligence (AI) technologies, building brand trust, and different approaches for achieving higher privacy competence scores.
See how organizational priorities and strategic approaches to data security and privacy are evolving around the globe.
This webinar will review:
- The top 10 privacy insights from the fifth annual Global Privacy Benchmarks Survey
- The top challenges for privacy leaders, practitioners, and organizations in 2024
- Key themes to consider in developing and maintaining your privacy program
Driving Business Innovation: Latest Generative AI Advancements & Success StorySafe Software
Are you ready to revolutionize how you handle data? Join us for a webinar where we’ll bring you up to speed with the latest advancements in Generative AI technology and discover how leveraging FME with tools from giants like Google Gemini, Amazon, and Microsoft OpenAI can supercharge your workflow efficiency.
During the hour, we’ll take you through:
Guest Speaker Segment with Hannah Barrington: Dive into the world of dynamic real estate marketing with Hannah, the Marketing Manager at Workspace Group. Hear firsthand how their team generates engaging descriptions for thousands of office units by integrating diverse data sources—from PDF floorplans to web pages—using FME transformers, like OpenAIVisionConnector and AnthropicVisionConnector. This use case will show you how GenAI can streamline content creation for marketing across the board.
Ollama Use Case: Learn how Scenario Specialist Dmitri Bagh has utilized Ollama within FME to input data, create custom models, and enhance security protocols. This segment will include demos to illustrate the full capabilities of FME in AI-driven processes.
Custom AI Models: Discover how to leverage FME to build personalized AI models using your data. Whether it’s populating a model with local data for added security or integrating public AI tools, find out how FME facilitates a versatile and secure approach to AI.
We’ll wrap up with a live Q&A session where you can engage with our experts on your specific use cases, and learn more about optimizing your data workflows with AI.
This webinar is ideal for professionals seeking to harness the power of AI within their data management systems while ensuring high levels of customization and security. Whether you're a novice or an expert, gain actionable insights and strategies to elevate your data processes. Join us to see how FME and AI can revolutionize how you work with data!
Main news related to the CCS TSI 2023 (2023/1695)Jakub Marek
An English 🇬🇧 translation of a presentation to the speech I gave about the main changes brought by CCS TSI 2023 at the biggest Czech conference on Communications and signalling systems on Railways, which was held in Clarion Hotel Olomouc from 7th to 9th November 2023 (konferenceszt.cz). Attended by around 500 participants and 200 on-line followers.
The original Czech 🇨🇿 version of the presentation can be found here: https://www.slideshare.net/slideshow/hlavni-novinky-souvisejici-s-ccs-tsi-2023-2023-1695/269688092 .
The videorecording (in Czech) from the presentation is available here: https://youtu.be/WzjJWm4IyPk?si=SImb06tuXGb30BEH .
Programming Foundation Models with DSPy - Meetup SlidesZilliz
Prompting language models is hard, while programming language models is easy. In this talk, I will discuss the state-of-the-art framework DSPy for programming foundation models with its powerful optimizers and runtime constraint system.
Dive into the realm of operating systems (OS) with Pravash Chandra Das, a seasoned Digital Forensic Analyst, as your guide. 🚀 This comprehensive presentation illuminates the core concepts, types, and evolution of OS, essential for understanding modern computing landscapes.
Beginning with the foundational definition, Das clarifies the pivotal role of OS as system software orchestrating hardware resources, software applications, and user interactions. Through succinct descriptions, he delineates the diverse types of OS, from single-user, single-task environments like early MS-DOS iterations, to multi-user, multi-tasking systems exemplified by modern Linux distributions.
Crucial components like the kernel and shell are dissected, highlighting their indispensable functions in resource management and user interface interaction. Das elucidates how the kernel acts as the central nervous system, orchestrating process scheduling, memory allocation, and device management. Meanwhile, the shell serves as the gateway for user commands, bridging the gap between human input and machine execution. 💻
The narrative then shifts to a captivating exploration of prominent desktop OSs, Windows, macOS, and Linux. Windows, with its globally ubiquitous presence and user-friendly interface, emerges as a cornerstone in personal computing history. macOS, lauded for its sleek design and seamless integration with Apple's ecosystem, stands as a beacon of stability and creativity. Linux, an open-source marvel, offers unparalleled flexibility and security, revolutionizing the computing landscape. 🖥️
Moving to the realm of mobile devices, Das unravels the dominance of Android and iOS. Android's open-source ethos fosters a vibrant ecosystem of customization and innovation, while iOS boasts a seamless user experience and robust security infrastructure. Meanwhile, discontinued platforms like Symbian and Palm OS evoke nostalgia for their pioneering roles in the smartphone revolution.
The journey concludes with a reflection on the ever-evolving landscape of OS, underscored by the emergence of real-time operating systems (RTOS) and the persistent quest for innovation and efficiency. As technology continues to shape our world, understanding the foundations and evolution of operating systems remains paramount. Join Pravash Chandra Das on this illuminating journey through the heart of computing. 🌟
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on automated letter generation for Bonterra Impact Management using Google Workspace or Microsoft 365.
Interested in deploying letter generation automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUpanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-notes-und-domino-lizenzkostenreduzierung-in-der-welt-von-dlau/
DLAU und die Lizenzen nach dem CCB- und CCX-Modell sind für viele in der HCL-Community seit letztem Jahr ein heißes Thema. Als Notes- oder Domino-Kunde haben Sie vielleicht mit unerwartet hohen Benutzerzahlen und Lizenzgebühren zu kämpfen. Sie fragen sich vielleicht, wie diese neue Art der Lizenzierung funktioniert und welchen Nutzen sie Ihnen bringt. Vor allem wollen Sie sicherlich Ihr Budget einhalten und Kosten sparen, wo immer möglich. Das verstehen wir und wir möchten Ihnen dabei helfen!
Wir erklären Ihnen, wie Sie häufige Konfigurationsprobleme lösen können, die dazu führen können, dass mehr Benutzer gezählt werden als nötig, und wie Sie überflüssige oder ungenutzte Konten identifizieren und entfernen können, um Geld zu sparen. Es gibt auch einige Ansätze, die zu unnötigen Ausgaben führen können, z. B. wenn ein Personendokument anstelle eines Mail-Ins für geteilte Mailboxen verwendet wird. Wir zeigen Ihnen solche Fälle und deren Lösungen. Und natürlich erklären wir Ihnen das neue Lizenzmodell.
Nehmen Sie an diesem Webinar teil, bei dem HCL-Ambassador Marc Thomas und Gastredner Franz Walder Ihnen diese neue Welt näherbringen. Es vermittelt Ihnen die Tools und das Know-how, um den Überblick zu bewahren. Sie werden in der Lage sein, Ihre Kosten durch eine optimierte Domino-Konfiguration zu reduzieren und auch in Zukunft gering zu halten.
Diese Themen werden behandelt
- Reduzierung der Lizenzkosten durch Auffinden und Beheben von Fehlkonfigurationen und überflüssigen Konten
- Wie funktionieren CCB- und CCX-Lizenzen wirklich?
- Verstehen des DLAU-Tools und wie man es am besten nutzt
- Tipps für häufige Problembereiche, wie z. B. Team-Postfächer, Funktions-/Testbenutzer usw.
- Praxisbeispiele und Best Practices zum sofortigen Umsetzen
Skybuffer SAM4U tool for SAP license adoptionTatiana Kojar
Manage and optimize your license adoption and consumption with SAM4U, an SAP free customer software asset management tool.
SAM4U, an SAP complimentary software asset management tool for customers, delivers a detailed and well-structured overview of license inventory and usage with a user-friendly interface. We offer a hosted, cost-effective, and performance-optimized SAM4U setup in the Skybuffer Cloud environment. You retain ownership of the system and data, while we manage the ABAP 7.58 infrastructure, ensuring fixed Total Cost of Ownership (TCO) and exceptional services through the SAP Fiori interface.
Digital Marketing Trends in 2024 | Guide for Staying AheadWask
https://www.wask.co/ebooks/digital-marketing-trends-in-2024
Feeling lost in the digital marketing whirlwind of 2024? Technology is changing, consumer habits are evolving, and staying ahead of the curve feels like a never-ending pursuit. This e-book is your compass. Dive into actionable insights to handle the complexities of modern marketing. From hyper-personalization to the power of user-generated content, learn how to build long-term relationships with your audience and unlock the secrets to success in the ever-shifting digital landscape.
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxSitimaJohn
Ocean Lotus cyber threat actors represent a sophisticated, persistent, and politically motivated group that poses a significant risk to organizations and individuals in the Southeast Asian region. Their continuous evolution and adaptability underscore the need for robust cybersecurity measures and international cooperation to identify and mitigate the threats posed by such advanced persistent threat groups.
Generating privacy-protected synthetic data using Secludy and MilvusZilliz
During this demo, the founders of Secludy will demonstrate how their system utilizes Milvus to store and manipulate embeddings for generating privacy-protected synthetic data. Their approach not only maintains the confidentiality of the original data but also enhances the utility and scalability of LLMs under privacy constraints. Attendees, including machine learning engineers, data scientists, and data managers, will witness first-hand how Secludy's integration with Milvus empowers organizations to harness the power of LLMs securely and efficiently.
Generating privacy-protected synthetic data using Secludy and Milvus
MariaDB training
1. MariaDB Training
Por Samuel dos Santos Tolentino
Dba Oracle / Sql Server / MySql
samuelsantostolentino@gmail.com
samuel.tolentino@lcs.com.br
Linkedin
2. Conteúdo
Lição 1: Instalação e configuração do MariaDB Pos-instalação
Lição 2: Administração
Lição 3: Banco de dados
Lição 4: Manipulação de dados e estruturas
Lição 5: Índices e estatísticas de tabela
Lição 6: Controle de transações
Lição 7: Gerenciando duplicidade
Lição 8: Métodos de backup e recuperação
Lição 9: Replicação
Lição 10: Auditoria
Lição 11: Procedures , functions e triggers
Lição 12 Tuning SQL: Explain
Apêncices
3. MariaDB Training
Lição 1:Instalação e configuração do MariaDB Pos-instalação
• Instalação do Mariadb
• Atualização
Lição 2: Administração
• Gerenciando usuários e privilégios.
• Arquivo de configuração (my.cnf)
• Comandos administrativos
Lição 3: Banco de dados
• Criação de banco de dados
• Exclusão de banco de dados
4. MariaDB Training
Lição 4: Manipulação de dados e estruturas
• Tipos de dados
• Select, Insert, update, delete
• Expressões Regulares
• Funções simples
• Funções de agrupamento
• Operadores de conjunto (Set operators)
• Sub query
• Operadores IN, ANY, ALL
• Views
• Criação e alteração e esclusão de tabelas
• Instrução Truncate table
• Criação de tabela temporária
• Exclusão de tabela temporária
5. MariaDB Training
Lição 5: Índices e estatísticas de tabela
• Criação de índice
• Exclusão de índice
• Rebuild índice
• Estatísticas de tabela
Lição 6: Controle de transações
• Estrutura das transações
• Commit, Rolback e Start transaction
• Processlist
Lição 7: Gerenciando duplicidade
• Utilizando insert
• Utilizando Insert ignore
• Utilizando Distinct
6. MariaDB Training
Lição 8: Métodos de backup e recuperação
• Ferramentas de backup
• Utilizando Select into out file(Aquivo externo)
Lição 9: Replicação
• Configuração de replicação master-slave
• Configuração de replicação master-master
• Monitoração da replicação
• Troubleshooting de replicação
Lição 10: Auditoria
• Plugins
• Instalação e configuração do audit plugin.
Lição 11: Procedures , functions e triggers
• Visão geral
• Exemplos
Lição 11: Tuning SQL
• Explain
7. Lição 1: Instalação do MariaDB
Os seguintes passos irão mostrar como efetuar a instalação do MariaDB no CentOs 7 utilizando o repositório
MariaDB:
1. Logue no SO com as credenciais de root:
Digite o comando: touch /etc/yum.repos.d/MariaDB.repo <enter>
vi /etc/yum.repos.d/MariaDB.rep <enter>
Adicione o conteúdo abaixo no arquivo:
[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.1/centos7-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1
Salve o arquivo.<esc> :wq <enter>
8. Lição 1:Instalação do MariaDB
2. Instale o MariaDB pelo utilitário yum:
sudo yum install MariaDB-server MariaDB-client -y
3. Inicie o serviço:
# systemctl start mariadb ou
# systemctl start mysql
4. Execute o comando mysql_secure_installation para configurar a instância.
[root@localhost ~]# mysql_secure_installation
Enter current password for root (enter for none):
OK, successfully used password, moving on...
Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.
9. Lição 1:Instalação do MariaDB
You already have a root password set, so you can safely answer 'n'.
Change the root password? [Y/n] y
New password:
Re-enter new password:
Password updated successfully!
Reloading privilege tables..
... Success!
Remove anonymous users? [Y/n] y
... Success!
Remove test database and access to it? [Y/n] n
... skipping.
Disallow root login remotely? [Y/n] y
... Success!
Reload privilege tables now? [Y/n] y
... Success!
Cleaning up...
All done! If you've completed all of the above steps, your MariaDB
installation should now be secure.
10. Lição 1: Acessando o banco de dados via
command line
Abra o terminal no Linux e digite:
mysql –uroot -p
onde -u indica o usuário e -p a senha conforma abaixo:
[root@teampass ~]# mysql -uroot -p
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or g.
Your MariaDB connection id is 64
Server version: 10.0.32-MariaDB MariaDB Server
Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.
MariaDB [(none)]>
11. Lição 1:Alterando o diretório de dados
# vi /etc/selinux/config
...
SELINUX=disabled
...
# reboot
# systemctl stop mysql
# mkdir /mysql
# chown -R mysql:mysql /mysql
# vi /etc/my.cnf
...
datadir=/mysql
...
# cp -R -p -v /var/lib/mysql/* /mysql/
# systemctl start mysql
12. Lição 1: Atualização do MariaDB
Para Atualizara versão do MariaDB basta alterar o repositório do yum (mariadb.repo).
# vi /etc/yum.repos.d/mariadb.repo
Altere a versão no repositório, salve.
[root@teampass ~]# systemctl stop mysql
[root@teampass ~]# sudo yum update (demora mais pois irá atualizar todo o S.O.) ou yum update MariaDB*
[root@teampass ~]# systemctl start mysql
[root@teampass ~]# mysql_upgrade -u root -p
13. Lição 2: Gerenciando Usuários
Sintaxe para criação de usuário no MariaDB:
CREATE USER ben@localhost IDENTIFIED BY 'p@$$w0rd';
Onde: @localhost indica que o usuário ben só pode conectar ao banco de dados a partir do servidor local.
Remoção de usuário:
Drop USER ben;
Renomear usuário:
remane user usuario_a to usuario_b ;
Alterar a senha do usuário:
SET PASSWORD FOR usuario_a = Password('n3w p@$$w0rd');
14. Lição 2: Privilégios
Após a criação da conta de usuário x, para que este possa acessar os objetos dos
bancos de dados é necessário conceder os devidos privilégios.
Exemplo:
grant select, insert, update, delete on database1 to user@localhost;
grant select, insert, update, delete on database1 to user@localhost with grant option;
Flush privileges;
Para verificar os privilégios concedidos a um determinado usuário:
SHOW GRANTS;
SHOW GRANTS FOR CURRENT_USER;
SHOW GRANTS FOR CURRENT_USER();
Remover privilégios:
REVOKE ALL PRIVILEGES, GRANT OPTION FROM user [, user] ...
O comando “show privileges “ mostra os privilégios suportados pelo MariaDB.
Exemplo no próximo slide:
16. Lição 2: Privilégios
Roles
Uma role server para agrupar uma serie de privilégios facilitando o
gerenciamento na concessão e retirada de privilégios.
Sintaxe:
CREATE [OR REPLACE] ROLE [IF NOT EXISTS] role
[WITH ADMIN
{CURRENT_USER | CURRENT_ROLE | user | role}]
Exemplos:
create role developer whith admin smith (cria a role com usuário admin
smith)
grant create table on database1 to developer; (Concede o privilégio de criar
tabela)
GRANT SELECT ON data.* TO developer; (Concede privilegio no banco de dados
data para a role)
grant developer to user1; (Concede acesso a todas a permissões e a role
possui)
drop role developer; (Remove a role do banco de dados)
Documentação:
Grant
Revoke
Roles
Conforme imagem abaixo é preciso executar o
comando set role para que e role tenha efeito.
17. Lição 2: Arquivo de configuração
O arquivo de configuração (my.cnf) é onde são armazenadas as configurações de inicialização da instância,
toda vez que o database é iniciado esse arquivo é lido e os valores das variáveis do sistema são carregados na
instância. A maioria das variáveis podem ser configuradas pelo arquivo my.cnf, mas a maioria não estarão
visíveis no arquivo, quando isso ocorre a instância é inicializada a partir de valores padrão. Algumas variáveis
podem ser alteradas dinamicamente, outras devem ser alteradas no arquivo my.cnf e após reiniciar a
instância.
O caminho padrão desse arquivo é /etc/my.cnf (Linux).
Exemplo de arquivo de configuração:
# Exemplo de arquivo de configuração mysql.
[servidor cliente]
socket = / tmp / mysql-dbug.sock
porta = 3307
# Isso será passado para todos os clientes mysql
[cliente]
senha = my_password
# Aqui estão as entradas para alguns programas específicos
# Os valores a seguir assumem que você tem pelo menos 32M de ram
18. Lição 2: Arquivo de configuração
# O servidor MySQL
[mysqld]
temp-pool
key_buffer_size = 16M
datadir = / my / mysqldata
loose-innodb_file_per_table
[mysqldump]
max_allowed_packet = 16M
[mysql]
no-auto-rehash
loose-abort-source-on-error
Todas as opções do servidor em my.cnf devem ser após a seguinte linha: [mysqld]
O comando “show variables” lista todas as variáveis de sistema.
https://mariadb.com/kb/en/library/server-system-variables/
19. Lição 2: Comandos administrativos
A lista abaixo mostra alguns comandos importantes que são mais utilizados:
Use [database name] : seleciona um database padrão para a sessão atual.
Show databases: lista todos os databases na instância atual.
Show tables: Lista todas as tabelas não temporárias do database atual selecionado.
Show columns from [table] ou describe ou desc [table]:Mostra a estrutura de colunas
da tabela informada.
Show table status like [‘table’]g: Fornece informações de tabelas não temporárias.
Show erros, Show warnings: Exibe erros, avisos e notas.
20. Lição 2: Mysqladmin
O mysqladmin é um utilitário de administração que serve para auxiliar na administração da instância e pode ser
usado para:
• Monitorar o que os clients do MariaDB estão fazendo (lista de processos)
• Obteter estatísticas de uso e variáveis do servidor MariaDB
• Criar / remover bases de dados
• Redefinir logs, estatísticas e tabelas
• Eliminar as consultas em execução.
• Parar o servidor (desligamento)
• Start / stop slaves
• Verificar se o servidor está ativo (ping)
https://mariadb.com/kb/en/library/mysqladmin/
Exemplos:
[root@master ~]# (mysqladmin -uroot -p shutdown Efetua um desligamento limpo na instância)
[root@master ~]# mysqladmin -u root -p create test (Cria um database)
[root@master ~]# mysqladmin -u root -p --relative --sleep=1 extended-status | grep -v " 0 “ (Lista variaveis de systema e
seus valores)
[root@master ~]# mysqladmin -uroot -proot variables | grep datadir (consulta variável de sistema)
[root@master ~]#
21. Lição 3: Criação de banco de dados
Create database sintaxe:
CREATE [OR REPLACE] {DATABASE | SCHEMA} [IF NOT EXISTS] db_name
[create_specification] ...
create_specification:
[DEFAULT] CHARACTER SET [=] charset_name
| [DEFAULT] COLLATE [=] collation_name
Exemplo:
Create database if not exists teste;
MariaDB [(none)]> show create database teste;
+----------+------------------------------------------------------------------+
| Database | Create Database |
+----------+------------------------------------------------------------------+
| teste | CREATE DATABASE `teste` /*!40100 DEFAULT CHARACTER SET latin1 */ |
+----------+------------------------------------------------------------------+
1 row in set (0.00 sec)
MariaDB [(none)]>
22. Lição 3: Character set e Collations
Um Character set é conjunto de caracteres enquanto uma Collation são as regras para comparar e classificar um
conjunto de caracteres específico.
Por exemplo, um subconjunto de um conjunto de caracteres pode consistir nas letras A, Be C. Um agrupamento
padrão pode definir estes como aparecendo em uma ordem ascendente de A, B, C.
Se o character set for omitido na criação do database o MariaDB assume por padrão o latin1.
https://mariadb.com/kb/en/library/character-set-and-collation-overview/
23. Licão 3: Alteração e Exclusão do banco de dados
Para excluir o banco de dados:
Sintaxe:
DROP {DATABASE | SCHEMA} [IF EXISTS] db_name
Exemplo:
MariaDB [(none)]> Drop database teste;
Query OK, 0 rows affected (0.00 sec)
Para alterar o banco de dados:
Sintaxe:
ALTER {DATABASE | SCHEMA} [db_name]
alter_specification ...
ALTER {DATABASE | SCHEMA} db_name
UPGRADE DATA DIRECTORY NAME
alter_specification:
[DEFAULT] CHARACTER SET [=] charset_name
| [DEFAULT] COLLATE [=] collation_name
Exemplo:
ALTER DATABASE test CHARACTER SET = 'utf8' COLLATE = 'utf8_bin';
24. Lição 4: SQL
O que é SQL?
SQL significa Structure Query Language, ou seja, linguagem de consulta estruturada, que foi desenvolvida
especificamente para comunicação de sistemas de banco de dados:
• Tem o objetivo de fornecer uma forma simples de ler e gravar informações no banco de dados.
• A forma mais utilizada de SQL é o padrão ANSI (American National Standards Institute), embora a maioria dos
SGBDs tenha seu próprio padrão SQL como Oracle e SQL Server, nos últimos anos anos cada vez mais tem se visto
o uso do padrão ANSI.
https://www.ansi.org/about_ansi/introduction/introduction?menuid=1
25. Lição 4: Colunas e Tipos de dados
Coluna: uma coluna é um campo único na tabela. Todas as tabelas possuem uma ou varias colunas. As colunas
podem armazenar diversos tipos de informação como: numéricos, binários, alfanuméricos, long, data e hora
etc.. Para informações detalhadas consulte a documentação do MariaDB.
Linha: os dados são armazenados nas tabelas em forma de linhas, cada registro salvo no banco de dados é
armazenado uma nova linha na tabela.
Null: Quando uma coluna tem a informação null significa a ausência de valor, ou seja, não possui informação
armazenada.
Primary Keys: uma primary key é uma ou um conjunto de colunas cujos valores únicos identificam cada linha na
tabela, os valores de uma primary key não podem se repetir.
Foreign Keys: uma foreign key é uma ou mais colunas que referenciam uma coluna em outra tabela onde a outra
tabela é denominada tabela pai e a tabela que contém a foreign key tabela filho.
Unique Keys: Uma unique key indica que cada registro do campo que está como unique não pode se repetir.
https://mariadb.com/kb/en/library/data-types/
26. Lição 4 Manipulação de dados: Select.
O select statement é um comando utilização para ler dados de uma ou mais tabelas do banco de dados.
Basicamente quando se utiliza o comando select no mínimo duas informações são necessárias: Quais informações
ler do banco e onde estão.
Sintaxe:
27. Exemplos:
Esse exemplo retorna todas as linhas e colunas da tabela customer. Onde * pode ser utilizado para
retornar todos os registros das tabelas.
O exemplo ao lado recupera apenas duas
colunas da tabela, mas todas as linhas
ainda. Para limitar o número de linhas
podemos utilizar a clausula where ou o
comando limit. Exemplo no próximo
slide.
28. O primeiro exemplo acima recupera os dados de um id especificado no where já o segundo traz todos
os registros mas limita o resultado para cinco linhas.
A clausula where é utilizada para dar uma condição para a query no intuito de restringir o número
de registros afetados, ou recuperar apenas registros específicos.
O comando limit apenas limita o número de linhas retornadas
29. Lição 4 Manipulação de dados: Expressões regulares
Expressões regulares permitem que a MariaDB execute uma correspondência de padrões complexos em uma string. Em
muitos casos, a combinação de padrões simples fornecida por LIKE é suficiente.
Exemplo:
https://mariadb.com/kb/en/library/regexp/
Mais: https://mariadb.com/kb/en/library/regexp/
30. Lição 4: Manipulação de dados: insert, update, delete
O comando insert é utilizado para inserir novos registros (linhas) na tabela.
O comando update é utilizado para modificar os valores existentes de um ou mais registros da tabela.
O comando delete é utilizado para apagar uma ou mais registros da tabela.
Exemplos:
MariaDB [(none)]> INSERT INTO customers(cust_name,cust_address,cust_city,cust_state,cust_zip,cust_country,cust_contact,cust_email)
MariaDB [(none)]> VALUES('Pep E. LaPew','100 Main Street','Los Angeles','CA','90046','USA',NULL,NULL);
MariaDB [(none)]> INSERT INTO Customers VALUES(NULL,'Pep E. LaPew','100 Main Street','Los Angeles','CA','90046','USA',NULL,NULL);
MariaDB [(none)]> Update customer set cust_address= ‘new address’ where custid = 1;
MariaDB [(none)]> Update customer set cust_address= ‘new address’ , custname=‘new name’ where custid = 1;
MariaDB [(none)]> Delete from customers where custid=1;
Nota: Muito cuidado! nos comandos delete e update, caso a cláusula where seja omitida, o comando irá apagar ou alterar todos
os registros(linhas) da tabela. Falaremos mais sobre a clausula where nos próximos capítulos.
31. Lição 4 Manipulação de dados: Clausulas like e
order by
A clausula order by é utilizada para ordenar o resultados das consultas que pode ser ascendente por padrão, ou
descendente. A clausula order by deve ser inserida sempre no final da query.
A clausula like é utilizada para comparação de igualdade entre strings, para encontrar um determinado padrão
de string.
Exemplos:
> Select * from customer where first_name like ‘A%’
> Select * from customer where first_name like ‘B_%a’
> Select First_name, Last_name from employess order by first_name desc.
> Select First_name, Last_name from employess order by first_name 2;
32. Lição 4 Manipulação de dados: Joins
Utilizamos Joins quando queremos ler dados em mais de uma tabela. Utilizaremos o padrão ANSI para
exemplificar.
A seguir alguns tipos de joins utilizados:
Inner join: Relacionamento de igualdade entre duas tabelas.
Self join: Auto Relacionamento, ou seja, uma tabela se relacionando com ela mesma.
Left join: Produz um conjunto de resultados com todas as linhas da tabela na "esquerda" (t1) mesmo que
não haja correspondência na tabela da direita. Se nenhuma correspondência for encontrada, todas as
colunas da tabela direita serão definidas com valor NULL.
Right Join: O oposto de left join, produz um conjunto de resultados com todas as linhas na tabela direita
mesmo que não haja correspondência na tabela da esquerda. Se nenhuma correspondência for
encontrada, todas as colunas da tabela da esquerda serão definidas com o valor NULL.
Cross join: produz um conjunto de resultados em que cada linha em cada tabela é unida a cada linha da
outra tabela. Isso também é chamado de produto cartesiano . Na MariaDB, a palavra-chave CROSS pode
ser omitida, pois não faz nada. Qualquer JOIN sem uma cláusula ON ou where resulta em um CROSS
JOIN.
https://mariadb.com/kb/en/library/joining-tables-with-join-clauses/
https://mariadb.com/kb/en/library/more-advanced-joins/
33. Exemplos:
Exemplo join:
Select e.emp_name, d.department_name
from employees e join departments d on e.department_id=d.departmentid;
Exemplo left join;
Select e.emp_name, d.department_name
from employees e left join departments d on e.department_id=d.departmentid;
Exemplo right join
Select e.emp_name, d.department_name
from employees e right join departments d on e.department_id=d.departmentid;
Exemplo self join:
Select e.empname as employee, m empname as manager
from employees e join employees m on e.managerid =m.employeeid
Exemplo cross join:
Select * from departments cross join employees
34. Lição 4 Manipulação de dados: Funções simples
Funções simples são funções criadas no banco de dados para efetuar diversas funções como conversões
de dados numéricos para string, string para data e vice-versa, comparações e manipulação de strings. A
seguir alguns exemplos:
Funcão Descrição
INSTR Retorna a posição do primeiro exemplo de uma subsequência
UPPER Converte o texto para caixa alta(letras maiúsculas)
LOWER Converte o texto para caixa alta(letras minúsculas)
CAST Converte vários tipos de dados, números para texto, data para texto e vice versa
REPLACE Substitui caracteres determinados de uma string.
DATEDIFF Retorna a diferença em dias entre duas datas.
TIMESTAMPDIFF Retorna a diferença entre duas datas em minutos, horas,dias. Essa fução requer 3 parâmetros: o
tipo de dado retornado e data inicio e fim.
CONCAT Junta duas ou mais strings concatenadas.
DATE_FORMAT Ele formata a data de acordo com a cadeia de formato especificado.
SUBSTRING Retorna uma string a partir de uma ou duas posições ex: SUBSTRING(str,pos,len).
36. Lição 4 Manipulação de dados: Funções de
agrupamento.
As funções de agrupamento servem para sumarizar dados fazendo cálculos como soma, média obter valores
máximo e mínimo das colunas sem ter que recuperar todas as linhas. Em conjunto com as funções de
agrupamento utilizamos as clausulas group by e having.
Exemplos:
1 - Select max(salary) from employees;
2 - Select min(id) from employees;
3 - Select count(*), department from cgroup by department;
4 - Select avg(salary) from employees;
5 - Select count(employee_id), department from employees group by department having count(department) > 5;
No exemplo 1 e 2 o a consulta retorna o maior e o menor salário, no exemplo 2 o resultado irá mostrar a contagem de registros da tabela
employees agrupando por departamento.
No exemplo 5 acima a consulta irá retornar a quantidade de empregados por departamento nos departamento que tenham mais
de 5 empregados.
Nota: as colunas que não tem função de grupo devem estar especificadas no group by.
37. Lição 4: Operadores de conjunto
Os operadores de conjunto( set operators) são utilizados com base no livro SQL-99 complete, dessa forma o
conteúdo não se aplica diretamente ao MariaDB. Entre os set operators estão: Union, except e insersect.
<query expression>
{UNION | EXCEPT | INTERSECT}
[ ALL | DISTINCT ]
[ CORRESPONDING [ BY (<Column name list>) ] ]
<query expression>
Exemplos:
SELECT employee_name, salary FROM Employees
UNION
SELECT employee_name, salary FROM EmployeesHist;
SELECT boss_name, salary FROM Bosses
EXCEPT
SELECT employee_name, salary FROM Employees;
SELECT boss_name, salary FROM Bosses
INTERSECT
SELECT employee_name, salary FROM Employees;
38. CREATE TABLE Villas (
county char(5),
acreage DECIMAL(4,2),
price DECIMAL(8));
CREATE TABLE Mansions (
owner char(5),
acreage DECIMAL(4,2),
house_rating INT,
price DECIMAL(8));
villas values(‘Lacombe’,39.00,10000);
Insert into villas values(‘Stettler’,15.78,90000);
Insert into villas values(‘Roseland’,15.77,20000);
Insert into villas values(‘Victoria’,null,null);
Insert into villas values(‘Victoria’,null,null);
Insert into mansions values ('Bodnar',15.77,NULL,200000);
Insert into mansions values ('Melnyk',39.00,15,900000);
Insert into mansions values ('Skoreyko',39.00,0,900000);
Insert into mansions values ('Mudriy',NULL, NULL,NULL);
Exemplos:
SELECT * FROM Villas
UNION DISTINCT
SELECT * FROM Villas
ORDER BY acreage DESC;
SELECT price FROM Villas
EXCEPT ALL
SELECT price FROM Mansions;
SELECT DISTINCT price FROM Villas
EXCEPT ALL
SELECT DISTINCT price FROM Mansions;
SELECT * FROM Villas
INTERSECT CORRESPONDING
SELECT * FROM Mansions;
SELECT acreage, 'Villa' AS type
FROM Villas
UNION
SELECT acreage, 'Mansion' AS type
FROM Mansions;
39. Lição 4: Sub querys
Sub querys são usadas para especificar um valor (uma sub consulta escalar, que retorna um valor), uma linha (a sub
consulta de linha, que retorna uma linha) ou uma Tabela (a sub consulta da tabela, que retorna uma tabela de
resultados) . É possível utilizar sub consultas em colunas no select, na clausula where, having e from.
Exemplos:
SELECT Table_1 . column_1 ,
Table_1 . column_2
FROM Table_1 WHERE Table_1 . column_1 =
( SELECT column_1 FROM Table_2
WHERE Table_2 . column_1 = 5 );
SELECT e.`empname`,(SELECT depname FROM departments
d WHERE d.id= e.`depid` )
FROM employees e (esta sub query é denominada sub query correlacionada
onde a sub consulta será executada para cada resultado
na consulta original)
40. Lição 4: Operadores IN, ANY, ALL, between
Os operadores in, any e all são utilizados na clausula where quando a condição da query tiver mais de um resulado
para comparar.
Exemplo:
SELECT salary FROM employees WHERE salary IN(SELECT AVG(salary) FROM employees GROUP BY depid);
Select salary from employees where salary > any (select AVG(salary) from employees group by departments);
Select salary from employees where salary > all (select AVG(salary) from employees group by departments);
SELECT salary FROM employees WHERE salary between 1000 and 4000;
Onde:
• any retorna registros onde o salário é maior do que o menor valor.
• In retorna retorna registros onde o salário seja igual a algum dos os valores retornados na subconsulta.
• All retorna registros onde o salário é maior do que o maior valor.
• Between retorna registros onde o salário esteja entre 1000 e 4000.
41. Lição 4 Views
Views são consideradas tabelas virtuais, diferente das tabelas que contém dados, as views não possuem dados, as
views possuem queries que retornam os dados dinamicamente quando são utilizadas.
Por que utilizar views?
• Para reuso de consultas SQL;
• Para segurança, restringindo campos da tabela;
• Para simplificar operações sql complexas, uma vez escrita a consulta sql, ela pode ser facilmente utilizada sem a
necessidade de saber os detalhes da consulta.
• Para modificar a formatação das informações, view podem formatar e apresentar dados diferente de como estão
nas tabelas.
42. Sintaxe:
CREATE
[OR REPLACE]
[ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]
[DEFINER = { user | CURRENT_USER | role | CURRENT_ROLE }]
[SQL SECURITY { DEFINER | INVOKER }]
VIEW [IF NOT EXISTS] view_name [(column_list)]
AS select_statement
[WITH [CASCADED | LOCAL] CHECK OPTION]
Exemplo:
Create or replace view v_name_view as
Select first_name, last_name, phone_number from customer;
Select * from v_name_view;
Nota: Não é possível criar mais de uma view com o mesmo nome, a utilização da palavra replace sobrescreve a view caso
já exista uma com o mesmo nome, já [IF NOT EXISTS] só permite criar a view caso não exista uma view com o mesmo
nome.
43. Criação de view com check option
Por padrão é possível atualizar uma tabela a partir de uma view, desde que na view não contenha joins ou agrupamentos, a
palavra chave with grant option previne a atualização da tabela a partir da view a menos que a clausula where seja
verdadeira.
Exemplo:
Create or replace view v_view_name as
MariaDB [teste]> CREATE VIEW view_check1 AS SELECT * FROM test WHERE cod <100;
CREATE VIEW view_check2 AS SELECT * FROM view_check1 WHERE cod > 10 with local check option;
Esta inserção é bem sucedida, uma vez que view_check2 apenas verifica a inserção contra view_check2, e a cláusula WHERE avalia como
verdadeira ( 150 é maior que10).
CREATE VIEW view_check3 AS SELECT * FROM view_check1 WHERE cod > 10 with cascaded check option;
INSERT INTO view_check3 VALUES (150);
Esta inserção falha, conforme view_check3 verifica a inserção contra ambas view_check3 as views subjacentes. A cláusula
WHERE para view_check1 avalia como falso ( 150 é maior que 10, mas 150 não é maior que100), de modo que a inserção
falha.
O select abaixo mostra se a view é atualizável, ou seja, se é possível manipular os dados da tabela;
MariaDB [teste]> SELECT TABLE_NAME,IS_UPDATABLE FROM INFORMATION_SCHEMA.VIEWS;
| TABLE_NAME | IS_UPDATABLE |
+-------------+--------------+
| view_check1 | YES |
| view_check2 | YES |
| view_check3 | YES |
+-------------+--------------+
3 rows in set (0.01 sec)
44. Lição 4 Criação de tabela
O comando create table cria uma tabela com o nome especificado, para criar tabela é preciso ter privilégio de
create table ou create table no banco de dados especifico.
Sintaxe:
CREATE [OR REPLACE] [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
(create_definition,...) [table_options ]... [partition_options]
CREATE [OR REPLACE] [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
[(create_definition,...)] [table_options ]... [partition_options]
select_statement
CREATE [OR REPLACE] [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
{ LIKE old_table_name | (LIKE old_table_name) }
select_statement:
[IGNORE | REPLACE] [AS] SELECT ...
Mais detalhes: https://mariadb.com/kb/en/library/create-table/
45. Exemplos:
USE teste;
Create table t1 (id int auto_increment primary key ,
name varchar(20) not null,
phone varchar(20)
);
O script acima cria uma tabela com campo id como chave primaria e auto incremento, ou seja, ao inserir registros não é
preciso informar valor para o campo id, not null indica que o campo não pode ser inserido sem dados.
USE teste;
CREATE TABLE t2 (id INT ,
cod INT,
NAME VARCHAR(20) NOT NULL,
phone VARCHAR(20),
PRIMARY KEY (id,cod)
foreign key (cod) references t1(cod)
);
O script acima mostra a criação da tabela com mais de uma coluna fazendo parte da primary key e criação de foreign key.
46. Lição 4 alteração de estrutura(Alter table)
O comando alter table serve para alterar a estrutura da tabela como por exemplo adicionar ou remover colunas
como também alterar o tipo de dado da coluna, adicionar primary key, foreign Keys
Exemplos:
MariaDB [teste]> use teste;
MariaDB [teste]> alter table t1 add (email varchar(50) ); -- (adiciona uma coluna)
MariaDB [teste]> alter table t2 drop column phone; -- (remove a coluna)
MariaDB [teste]> Alter table t1 modify name varchar(50); -- (modifica o tamanho da coluna)
MariaDB [teste]> alter table t1 add constraint t1_fk foreign key (cod) references t2(cod); --(adiciona foreign key)
MariaDB [teste]> alter table t2 add constraint t2_pk primary key(id); -- (adiciona primary key);
Nota: cada tabela pode conter apenas uma primary key, mas várias foreign keys, pode ter uma ou mais coluna compondo uma
primary key;
Mais exemplos:
https://mariadb.com/kb/en/library/alter-table/
47. Lição 4 Drop e Truncate table
O comando truncate table recria toda a estrutura da eliminando todos os registros, diferente do comando drop
table o truncate não permite que seja efetuado rollback das alterações. Falaremos mais de rollback no capitulo
controle de transações.
Exemplo Drop table:
MariaDB [teste]> use teste;
MariaDB [teste]> drop table test;
Query OK, 0 rows affected (0.01 sec)
Exemplo Truncate table:
MariaDB [teste]> use teste;
MariaDB [teste]> truncate table t1;
ERROR 1701 (42000): Cannot truncate a table referenced in a foreign key constraint (`teste`.`t2`, CONSTRAINT `t2_fk` FOREIGN KEY (`cod`) REFERENCES `teste`.`t1` (`id`))
MariaDB [teste]>
Nota: caso a tabela possua integridade referencial não é permitido executar o comando, nesse caso primeiro deve-se eliminar as foreign na
tabela filho, conforme exemplo abaixo. Caso exista coluna alto increment, a sequencia de incremento é reiniciada.
MariaDB [teste]> alter table t2 drop foreign key t2_fk;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
MariaDB [teste]>
MariaDB [teste]> truncate table t1;
Query OK, 0 rows affected (0.02 sec)
48. Lição 4 tabelas temporárias
Tabelas temporárias quando criadas existem até o termino da sessão atual, após o encerramento da sessão a tabela
é eliminada. Para excluir uma tabela temporária basta executar o comando drop temporary table table_name;
Exemplo:
49. Lição 5: Índices
Índices são utilizados para melhorar a velocidade em que uma consulta é retornada, existem quatro formas de criar
índices: chaves primárias, índices únicos, índices simples e índices de texto completo.
• Índices de Primary key: Toda vez que uma tabela é criada com chave primaria (Primary key), automaticamente é
criado um unique índex na coluna ou nas colunas que compõem a chave primária.
• Índices únicos: quando é criado uma unique key também é criado um índice único na coluna indicada.
• Índices simples: índices de colunas que não são únicas.
• Um índice de texto completo no MariaDB (full text index) é um índice do tipo FULLTEXT, e permite mais opções
ao procurar partes de texto de um campo. Os índices de texto completo podem ser usados apenas com as tabelas
MyISAM e Aria , no MariaDB 10.0.5, com as tabelas InnoDB no MariaDB 10.0.15 e podem ser criadas somente para
colunas CHAR , VARCHAR ou TEXT . As tabelas particionadas não podem conter índices de texto completo,
mesmo que o mecanismo de armazenamento os suporte.
https://mariadb.com/kb/en/library/fulltext-index-overview/
• Nota: Unique índices indicam que as informações nas colunas não podem se repetir tanto em primary Keys como
Unique Keys.
50. Exemplos
Os índices podem ser criados ou adicionados nas tabelas da seguinte forma:
Índices únicos:
MariaDB [hr]> ALTER TABLE Employees ADD UNIQUE `EmpCode`(`employee_id`);
ou
MariaDB [hr]> CREATE UNIQUE INDEX emp_email ON employees(email);
Indices simples:
MariaDB [hr]> CREATE INDEX emp_email ON employees(email);
Para remover índices:
MariaDB [hr]> alter table employees drop index emp_email;
51. Full text index
CREATE TABLE ft2(copy TEXT,FULLTEXT(copy)) ENGINE=MyISAM;
INSERT INTO ft2(copy) VALUES
('MySQL vs MariaDB database'),
('Oracle vs MariaDB database'),
('PostgreSQL vs MariaDB database'),
('MariaDB overview'),
('Foreign keys'),
('Primary keys'),
('Indexes'),
('Transactions'),
('Triggers');
Nesse exemplo, tudo o que está
associado à palavra "banco de dados" é
retornado quando a expansão da consulta
é usada, mesmo que não seja
explicitamente solicitada.
Mais exemplos: https://mariadb.com/kb/en/library/fulltext-index-overview/
52. Lição 5: Rebuild de Índices
Para efetuar o rebuild de índice no MariaDB, deve-se utilizar o comando optimize table que possui duas funções:
Desfragmentar a tabela e atualizar os índices de tabelas, porém tabelas InnoDB não suportam o optimize table.
Portanto o comando abaixo é um atalho para efetuar a organização completa da tabela mais a análise.
Onde o parâmetro –o indica o database.
Nota: O comando optimize table
loca a tabela, logo deve –se ter
cautela ao executar.
53. Lição 5: estatísticas de tabela
A declaração SHOW TABLE_STATISTICS foi introduzida no MariaDB 5.2 como parte do recurso Estatísticas de usuário .
Foi removido como uma declaração separada no MariaDB 10.1.1 , mas efetivamente substituído pela SHOW
information_schema_table declaração genérica .
O comando SHOW TABLE_STATISTICS G tabela mostra as estatísticas sobre o uso da tabela
Exemplo:
54. Lição 6: Controle de transações
"Uma transação SQL (transação) é uma sequência de execuções de instruções SQL que são atômicas em relação à
recuperação. Ou seja, o resultado de execução é completamente bem-sucedido ou não tem efeito em nenhum
efeito.(MariaDB)
O mecanismo de armazenamento InnoDB suporta transações compatíveis com ACID* .
Existem vários comandos para controle de transações no MariaDB. Nesse treinamento iremos falar de:
Commit, Rollback, Start transaction e lock tables.
Commit e Rollback: O comando commit indica o fim de uma transação informando ao banco de dados a instrução
para persistir os dados no disco, já o comando rollback indica exatamente ao contrário, ou seja desfaz
alterações efetuadas por transações que ainda não sofreram commit.
Start transaction: A declaração START TRANSACTION ou BEGIN inicia uma nova transação. COMMIT confirma a
transação atual, tornando suas mudanças permanentes. ROLLBACK desfaz a transação atual, cancelando suas
alterações. O comando SET autocommit desabilita ou habilita o modo de autocommit padrão para a sessão atual.
lock tables: O MariaDB permite que as sessões do cliente adquiram bloqueios de tabela explicitamente com o
objetivo de cooperar com outras sessões para acesso a tabelas ou para evitar que outras sessões modifiquem
tabelas durante períodos em que uma sessão requer acesso exclusivo a elas. Uma sessão pode adquirir ou liberar
bloqueios apenas para si. Uma sessão não pode adquirir bloqueios para outra sessão ou liberar bloqueios
mantidos por outra sessão. https://mariadb.com/kb/en/library/transactions/
* Atomicidade, consistência, isolamento e durabilidade.
55. Lição 6: Processlist
O comando SHOW [FULL] PROCESSLIST mostra quais processos estão em execução. Você também pode obter essas
informações da tabela information_schema.PROCESSLIST ou do comando mysqladmin processlist. Se você tiver o
privilegio PROCESS, você pode ver todos os processos. Caso contrário, você pode ver apenas seus próprios processos
(ou seja, processos associados à conta MariaDB que você está usando). Se você não usar a palavra - chave FULL,
apenas os primeiros 100 caracteres de cada declaração são mostrados no campo Informações.
Exemplo:
56.
57. Lição 7: Gerenciando duplicidade
A duplicidade pode ser a nível de tabela, quando a mesma possui mais de um registro com a mesma informação ou
na forma de select, quando o resultado de uma consulta escrita de forma incompleta implica em linhas duplicadas
no resultado.
O uso de primary keys e e unique Keys evitam que haja duplicidade de informações quando se insere um novo
registro. Para selects com duplicidade podemos utilizar o comando Distinct .
O comando “insert ignore” ignora o erro caso ao tentar inserir um registro duplicado em uma coluna única com
restrição unique.
Exemplos:
58. Lição 8: Métodos de backup e recuperação
No MariaDb é possível efetuar backups lógicos e físicos onde os backups lógicos efetuam backup apenas dos
dados e estruturas dos bancos enquanto que backups físicos efetuam o backup diretamente dos arquivos físicos
no disco.
A ferramenta utilizada para fazer backup no MariaDB é o mysqldump.
Executando um backup simples:
shell> mysqldump db_name > backup-file.sql (Efetua o backup de todo o database)
shell> mysqldump -u root -p PRODUCTS products_tbl > export_file.txt (Efetua o backup de apenas uma tabela especifica)
Executando restauração:
shell> mysql –u -p db_name < backup-file.sql
shell> mysqld -u root -p PRODUCTS products_tbl < export_file.tx
Por padrão o mysqldump loca as tabelas ao efetuar o backup, para evitar que sejam locadas as tabelas utiliza-se o
parâmetro –single-transaction:
Exemplo:
mysqldump -uroot -proot hr > hr.sql --single-transaction
59. Lição 8: Métodos de backup e recuperação
Efetuando select para um arquivo externo:
SELECT * FROM employees INTO OUTFILE ‘emp.txt’;
Este comando gera um arquivo emp.txt no diretório do banco de dados selecionado.
Outras ferramentas de backup:
Percona XtraBackup: a partir da versão 10.1
MariaDB Backup: a partir da versão 10.1
60. Lição 8: Métodos de backup e recuperação
Cold Backup:
# systemctl stop mysql
# mkdir /Backup
# cp -rfvp /var/lib/mysql/ /Backup/
# systemctl start mysql
Para restaurar o backup em outra maquina:
# systemctl stop mysql
Copie o backup da maquina original ou de onde ele está localizado para a maquina onde se deseja restaurar.
# scp -Cr /Backup/mysql/* 192.168.174.141:/var/lib/mysql/
# chown -R mysql:mysql /var/lib/mysql
# setenforce 0
inicie o MySQL.
# systemctl start mysql
61. Lição 9: Replicação
No MariaDB é possível fazer replicação do tipo master-slave onde o master envia as alterações para o slave e multi-
master que significa que o servidor tem vários mestres que se replicam.
O método de sincronização é efetuado de forma assíncrona através do envio de binlogs para os outros servidores
MariaDB o que pode causar inconsistências caso o envio dos logs seja interrompidos por falha de rede por exemplo.
Passos para configurar a replicação master-slave:
1- Configurar as os parâmetros de replicação no arquivo my.cnf:
2- Efetuar backup dos bancos de dados no master e restaurar no slave.
3- Criar usuário que fará a replicação e conceder privilégio.
4- Ativar a replicação a partir do servidor slave.
Passos para configurar a replicação master-master:
1- Configurar as os parâmetros de replicação no arquivo my.cnf em todos servers.
2- Efetuar backup dos bancos de dados no master1 e restaurar no master2.
3- Criar usuário que fará a replicação e conceder privilégio em todos servers.
4- Ativar a replicação a partir do servidor master1.
5- Ativar a replicação a partir do servidor master2.
62. Exemplo master-slave
Servidor master:
[root@master ~]# systemctl stop mysql
Edit my.cnf:
# bind-address = 127.0.0.1
Por padrão o mariadb irá aceitar apenas conexões do host local iremos comentar essa linha
para ser possível receber conexões de outros hosts
server-id = 1
report_host = master
essas variaveis irão receber o id do servidor e hostname e precisam ser únicas.
log_bin = /var/log/mysql/mariadb-bin
log_bin_index = /var/log/mysql/mariadb-bin.index
Enable binary logging.
relay_log = /var/log/mysql/relay-bin
relay_log_index = /var/log/mysql/relay-bin.index
Habilita a criação de arquivos de relay log, os eventos serão lidos no arquivo binlog do
servidor master e escritos no relay-log do servidor slave.
replicate-do-db = testdb
esse parâmetro indica quais databases serão replicados(opcional)
[root@master ~]# systemctl start mysql
[root@master ~]# mysql –uroot -p
MariaDB [(none)]> create user replusr@'%' identified by 'replusr';
MariaDB [(none)]> grant replication slave on *.* to replusr@'%';
MariaDB [(none)]> show master status; (guarde o resultado, será utilizado na habilitação da replicação)
63. Exemplo master-slave
Servidor slave:
[root@master ~]# systemctl stop mysql
Edit my.cnf:
Altere o server-id e o report_host
[root@master ~]# systemctl start mysql
[root@master ~]# mysql –uroot -p
MariaDB [(none)]> create user 'replusr'@'%' identified by 'replusr';
MariaDB [(none)]> grant replication slave on *.* to 'replusr'@'%';
MariaDB [(none)]> STOP SLAVE;
MariaDB [(none)]> CHANGE MASTER TO MASTER_HOST='192.168.174.139', MASTER_USER='replusr',
MASTER_PASSWORD='replusr', MASTER_LOG_FILE='mariadb-bin.000002', MASTER_LOG_POS=630;
MariaDB [(none)]> START SLAVE;
MariaDB [(none)]> SHOW SLAVE STATUS G;
Faça inserts no master e verifique se a replicação está funcionando.
64. Exemplo master-master
Os passos para configuração da replicação multi-master são basicamente os mesmos, o que muda é na hora de
habilitar a replicação nos dois ou mais lados e algumas variáveis a mais utilizadas na replicaçaão:
Server Master 1:
MariaDB [(none)]> STOP SLAVE;
MariaDB [(none)]> CHANGE MASTER ‘master2' TO MASTER_HOST='192.168.174.141', MASTER_USER='replusr',
MASTER_PASSWORD='replusr', MASTER_LOG_FILE='mariadb-bin.000002', MASTER_LOG_POS=630;
MariaDB [(none)]> START SLAVE ‘master1' ;
MariaDB [(none)]> SHOW SLAVE ‘master1' STATUS G;
Server Master 2:
MariaDB [(none)]> STOP SLAVE;
MariaDB [(none)]> CHANGE MASTER ‘master1’ TO MASTER_HOST='192.168.174.139', MASTER_USER='replusr',
MASTER_PASSWORD='replusr', MASTER_LOG_FILE='mariadb-bin.000002', MASTER_LOG_POS=630;
MariaDB [(none)]> START SLAVE ‘master2 ;
MariaDB [(none)]> SHOW SLAVE ‘master2 STATUS G;
Faça inserts dos dois lados e verifique se a replicação está funcionando.
65. Lição 9: Monitoramento da replicação
Alguns comando de replicação:
CHANGE MASTER ['connection_name'] TO .... Isso cria ou modifica uma conexão com um master.
FLUSH RELAY LOGS ['connection_name'] .... Libera ou recarrega os caches de memória usados pelo MariaDB.
RESET SLAVE ['connection_name'] [ALL]. Isso é usado para redefinir a posição de replicação slave ou para remover
um slave permanentemente.
SHOW SLAVE ['connection_name'] STATUS ... Mostra informações de um slave specífico
SHOW ALL SLAVES STATUS.... Mostra informações de todos os slaves.
START SLAVE ['connection_name'...]] Inicia a replicação no slave.
START ALL SLAVES ... Inicia a replicação em todos os slaves.
STOP SLAVE ['connection_name'] ... Para a replicação no slave.
STOP ALL SLAVES ... Para a replicação de todos os slaves.
SHOW MASTER STATUS ... Mostra status do master.
Mais: https://mariadb.com/kb/en/library/replication-commands/
66. Lição 9: Trobleshooting da replicação
Em caso de falha da replicação será necessário refazer a sincronização a partir do master que está consistente.
Tenha certeza de que o slave não esteja efetuando transações nesse momento pois do contrário pode ocorrer perda
de informação.
Restaurando os dados a partir do master.
1- Para bloquear todas as tabelas execute:
MariaDB [(none)]> FLUSH TABLES WITH READ LOCK;
MariaDB [(none)]> Show master status G
Exemplo saída:
MariaDB [(none)]> show master status G
*************************** 1. row ***************************
File: mariadb-bin.000003
Position: 328
mysqldump –uroot –p --add-drop-database test table1 table2 > testdump.sql
MariaDB [(none)]> unlock tables;
* Estas ações serão efetuadas no Master
67. 2- Copie o backup efetuado anteriormente no master e restaure o backup no slave:
MariaDB [(none)]> stop slave;
MariaDB [(none)]> mysql -u root -p my_database < my_database.sql
MariaDB [(none)]> show slave status G
MariaDB [(none)]> flush tables with read lock;
MariaDB [(none)]> show master status;
MariaDB [(none)]> change master to master_log_file=' mariadb-bin.000002 ', master_log_pos=1740;
MariaDB [(none)]> start slave <slave name>;
MariaDB [(none)]> show slave statusG
MariaDB [(none)]> unlock tables;
Outra forma simples de reiniciar a replicação após uma falha:
MariaDB [(none)]> SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1;
MariaDB [(none)]> START SLAVE;
!Porém é preciso verificar se as informações estão consistentes em ambas as bases;
68. Lição 10: Auditoria
Varias funcionalidades utilizadas no MariaDB são adicionas através da instalação de plugins como é o caso do plungin
de auditoria do banco de dados, basicamente o propósito do MariaDB Audit Plugin é registrar a atividade do servidor.
Para cada sessão de cliente, ele registra quem se conectou ao servidor (ou seja, nome de usuário e host), quais
consultas foram executadas e quais tabelas foram acessadas e variáveis de servidor que foram alteradas.
Pelo MariaDB Audit Plugin é possível audita as seguintes ações:
CONNECT: quando o usuário se conecta, desconecta ou se conecta com falhas - incluindo o código de erro.
QUERY : Consultas executadas e seus resultados em texto simples, incluindo consultas falhadas devido a erros de
sintaxe ou permissão.
TABLE : Tabelas afetadas pela execução da consulta
QUERY_DDL : O mesmo que QUERY, mas filtros apenas DDL do tipo consultas ( CREATE, ALTER, DROP, RENAME e
TRUNCATE- exceto CREATE/DROP [PROCEDURE / FUNCTION / USER] e RENAME USER (eles não são DDL) MariaDB
5.5.42, MariaDB 10.0.17 , MariaDB 10.1.4
QUERY_DML: consultas sql, mas filtros única DML-tipo ( DO, CALL, LOAD DATA/XML, DELETE, INSERT, UPDATE,
HANDLER e REPLACE) MariaDB 5.5.42 , MariaDB 10.0.17 , MariaDB 10.1.4
QUERY_DCL: comandos de DCL(Data control language), CREATE USER, DROP USER, RENAME USER, GRANT,
REVOKE,SET PASSWORD. MariaDB 5.5.43 , MariaDB 10.0.18 , MariaDB 10.1.5
Mais detalhes: https://mariadb.com/kb/en/library/mariadb-audit-plugin-log-settings/
69. Configurando o audit plugin:
1- passo conect no mariadb como root
INSTALL PLUGIN server_audit SONAME 'server_audit.so'; <enter>
2- edite o arquivo my.cnf (/etc/my.cnf) com os parâmetros:
plugin-load = server_audit= server_audit.so
server_audit_events = connect,query (ações que serão auditadas)
server_audit_file_path = /var/lib/mysql-logs/audit.log (local onde será gravado os logs de auditoria)
server_audit_file_rotate_size = 10G #set the size of the logfile (tamanho máximo do arquivo de log)
server_audit_logging = ON (Ativa a auditoria)
server_audit_file_rotations = 0 (ativa rotatividade do arquivo de log)
3- Reinicie o MariaDB
4- Configure o nível da auditoria.
MariaDB [(none)]> SET GLOBAL server_audit_events = 'CONNECT,QUERY,TABLE,QUERY_DDL,QUERY_DCL,QUERY_DML';
Query OK, 0 rows affected (0.00 sec)
Inclua as alterações no aquivo my.cnf
server_audit_events=connect,query,table,QUERY_DDL,QUERY_DCL,QUERY_DML
A partir de então todas as ações efetuadas serão gravadas no /var/lib/mysql-logs/audit.log de acordo com o nível
de auditoria configurado.
Nota: Caso haja replicação
configurada e se deseje auditar os
demais servidores o procedimento
deve ser efetuado em cada host.
70. Lição 11: Procedures , functions e triggers
Procedures: Procedures são procedimentos armazenados no banco de dados que podem ter Por padrão,
uma rotina está associada ao banco de dados atual em uso. Para associar um procedimento de forma
explícita a um dado banco de dados, especifique o nome como db_name.sp_name quando você o cria.
Functions: Uma função tem basicamente as mesmas funções de um procedimento, porém
obrigatoriamente a função sempre deverá retornar algum valor. Funções são muito uteis com cálculos,
mas poder retornar qualquer tipo de dado.
Triggers: Triggers são gatilhos que são disparados por eventos que acontecem nas tabelas
(inser,update,delete), para efetuar um conjunto de funções pré-programadas. Triggers podem ser
utilizadas para auditoria gravando logs de ações efetuadas nas tabelas do banco de dados.
71. Exemplo procedure
DELIMITER //
CREATE PROCEDURE simpleproc (out param1 INT)
BEGIN
SELECT COUNT(*) INTO param1 FROM t;
END;
//
DELIMITER ;
CALL simpleproc(@a);
SELECT @a;
+------+
| @a |
+------+
| 1 |
+------+
DELIMITER //
CREATE PROCEDURE simpleproc2 (
OUT param1 CHAR(10) CHARACTER SET 'utf8' COLLATE
'utf8_bin'
)
BEGIN
SELECT CONCAT('a',f1) INTO param1 FROM t;
END;
//
DELIMITER ;
DELIMITER //
CALL simpleproc2(@a);
SELECT @a "resulatado";
Exemplos extraídos da documentação MariaDB
72. Exemplo function
DELIMITER //
CREATE FUNCTION max_salary (dept l ) RETURNS INT RETURN
(SELECT MAX(salary) FROM employees WHERE employees.dept =
dept);
GRANT EXECUTE ON FUNCTION max_salary TO roger;
//
DELIMITER ;
DELIMITER //
CREATE FUNCTION hello (s CHAR(20))
RETURNS CHAR(50) DETERMINISTIC
RETURN CONCAT('Hello, ',s,'!');
//
DELIMITER ;
SELECT hello('world');
+----------------+
| hello('world') |
+----------------+
| Hello, world! |
+----------------+
73. Exemplo trigger
CREATE TRIGGER Books_Delete
AFTER DELETE ON Books /* ver nota (a) */
REFERENCING OLD ROW AS Old /* ver nota (b) */
FOR EACH ROW /* ver nota (c) */
INSERT INTO Books_Deleted_Log
VALUES (Old.title); /* ver nota (d) */
Nota (a): A ação da Trigger deve ser depois, uma vez que a ação Trigger inclui uma instrução SQL-data change.
Nota (b): é convencional usar o alias " Old" ou " Old_Row" para a linha anterior.
Nota (c): A ação será efetuada para cada linha alterada na tabela.
Nota (d): OLD é um alias para o valor antigo da coluna, assim OLD.TITLE é o valor antigo da coluna title.
CREATE TRIGGER Clients_Insert
BEFORE INSERT ON Clients
REFERENCING NEW ROW AS New
FOR EACH ROW
SET New.home_telephone =
COALESCE(New.home_telephone,New.work_telephone);
Exemplos extraídos da documentação do MariaDB
74. Lição 12 Tuning SQL: Explain
A declaração EXPLAIN pode ser usada como sinônimo de DESCRIBE ou como forma de obter informações sobre como
o MariaDB executa uma declaração SELECT(assim como UPDATE e DELETE desde MariaDB 10.0.5):
'EXPLAIN tbl_name‘ é sinônimo de DESCRIBE tbl_name ou SHOW COLUMNS FROM tbl_name
Quando você precede uma declaração SELECT (ou também com MariaDB 10.0.5 , um UPDATE ou um DELETE) com a
palavra-chave EXPLAIN, a MariaDB exibe informações do otimizador sobre o plano de execução da consulta. Ou
seja, MariaDB explica como ele processaria o SELECT, UPDATE ou DELETE incluindo informações sobre como as
tabelas são unidas e em qual ordem.
ANALYZE statement, que executa a consulta, bem como produzindo saída EXPLAIN, e fornece estatísticas reais, bem
como estimadas, está disponível no MariaDB 10.1.0 .
Sintaxe:
EXPLAIN tbl_name ou explain <instrução select>
75. Coluna Descricão
id Número de seqüência que mostra em que tabelas de pedidos são juntas.select_type Que tipo de
SELECTtabela vem.
table Alias nome da tabela. As tabelas temporárias materializadas para sub-consultas são denominadas
<subquery #>
type Como as linhas são encontradas a partir da tabela (tipo de junção).
possible_keys chaves na tabela que podem ser usadas para encontrar linhas na tabela
key O nome da chave que é usada para recuperar linhas. NULL Não foi utilizada nenhuma chave.
key_len Quantos bytes da chave que foi usada (mostra se estamos usando apenas partes da chave de várias
colunas).
ref A referência que é usada como o valor da chave.
rows Uma estimativa de quantas linhas encontraremos na tabela para cada pesquisa de chave.
Extra Informações adicionais sobre esta associação.
Descrição das colunas em explain select
Exemplos no próximo slide:
Quando você precede uma declaração SELECT (ou, a partir do MariaDB 10.0.5 , UPDATE ou DELETE também) com
a palavra-chave EXPLAIN, a MariaDB exibe informações do otimizador sobre o plano de execução da consulta.
Ou seja, MariaDB explica como ele processaria o SELECT, UPDATE ou DELETE incluindo informações sobre como as
tabelas são unidas e em qual ordem. Na tabela abaixo é mostrado a descrição de cada coluna do explain:
76.
77. Explain
A coluna “select_type” pode retornar os seguintes resultados:
DEPENDENT SUBQUERY
DEPENDENT UNION
DERIVED
MATERIALIZED
PRIMARY
SIMPLE
SUBQUERY
UNCACHEABLE SUBQUERY
UNCACHEABLE UNION
UNION
UNION RESULT
Nota: O EXPLAIN pode adquirir bloqueios de metadados da mesma maneira que SELECT faz, pois precisa conhecer
metadados de tabelas e, às vezes, dados também.
78. Explain
A coluna “type” pode retornar os seguintes resultados:
Valor Descrição
All Uma verificação completa de tabela é feita para a tabela (todas as linhas são lidas). Isso é ruim
se a tabela for grande e tiver feito join com uma tabela anterior! Isso acontece quando o
otimizador não conseguiu encontrar nenhum índice utilizável para acessar linhas.
eq_ref Um índice unico é usado para encontrar as linhas. Este é o melhor plano possível para encontrar
a linha.
fulltext Um índice de texto completo é usado para acessar as linhas.
Index_merge Um acesso de 'intervalo' é feito para vários índices e as linhas encontradas são mescladas. A
coluna da chave mostra quais chaves são usadas.
Index_subquery Isso é semelhante ao ref, mas usado para sub-consultas que são transformadas em pesquisas-
chave.
index Uma varredura completa sobre o índice usado. Melhor do que TODOS, mas ainda é ruim se o
índice for grande e a tabela se juntar a uma tabela anterior.
unique_subquery Isso é semelhante ao eq_ref, mas usado para sub-consultas que são transformadas em
pesquisas-chave
79. Explain
A coluna “Extra” pode retornar os seguintes resultados:
Valor Descrição
Distinct Se fosse utilizada otimização distinta (remover linhas duplicadas). Isso é marcado apenas para a última tabela
no SELECT.
Full scan on NULL key A tabela é uma parte da consulta secundária e se o valor que é usado para corresponder a sub-consulta
será NULL, faremos uma verificação de tabela completa.
Impossible HAVING A cláusula HAVING usada sempre é falsa, de modo SELECTque não retornará nenhuma linha.
Impossible WHERE A cláusula WHERE usada sempre é falsa, de modo que o SELECT não retornará nenhuma linha. Por
exemplo: WHERE const_column=5 e const_column teve um valor de 4.
Range
checked for each record (in
dex map: ...)
Isso acontece somente quando não houve um bom padrão de padrão de uso, mas pode haver algum índice que possa
ser usado quando podemos tratar todas as colunas da tabela anterior como constantes. Para cada combinação de
linhas, o otimizador irá decidir qual índice usar (se houver) para buscar uma linha dessa tabela. Isso não é rápido, mas
mais rápido do que uma verificação de tabela completa que é a única outra escolha. O mapa de índice é uma máscara
de bits que mostra qual índice é considerado para cada condição de linha.
Using filesort Uso de order by no select.
Using index Somente o índice é usado para recuperar as informações necessárias da tabela. Não é necessário realizar uma busca
extra para recuperar o registro real.
Using index for group-by O índice está sendo usado para resolver uma consulta GROUP BYou DISTINCT. As linhas não são lidas. Isso é muito
eficiente se a tabela tiver muitas entradas de índice idênticas, pois as duplicatas são rapidamente saltadas.
80. Explain
O explain também pode executar verificação a partir de uma thread ativa, caso essa esteja efetuando alguma ação
passível de otimização o explain recupera a declaração que está sendo executada e gera as informações do
otimizador em tempo real.
Exemplo:
SHOW EXPLAIN FOR 1;
+------+-------------+-------+-------+---------------+------+---------+------+---------+----------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+------+-------------+-------+-------+---------------+------+---------+------+---------+----------------------+
| 1 | SIMPLE | tbl | index | NULL | a | 5 | NULL | 1000107 | Using index |
+------+-------------+-------+-------+---------------+------+---------+------+---------+----------------------+
1 row in set, 1 warning (0.00 sec)
Também pode ser utilizado para mostrar os índices que uma tabela possui:
81.
82. Apêndice A: my.cnf
Neste apêndice mostraremos as variáveis mais utilizadas e qual a função essa variável possui:
Todas as variáveis do servidor MariaDB devem ser colocadas logo abaixo da linha [mysqld].
data_dir: Este parâmetro recebe o caminho o diretório para onde serão armazenado os arquivos de dados. O valor
padrão no Linux é /var/lib/mysql.
innodb_buffer_pool_size: Utiliza 80% da memória RAM disponível. Por padrão é inicializado com 70% da mamória.7
innodb_log_file_size: Ajuste esse parâmetro para 20% do tamanho do innodb_buffer_pool_size.
innodb_file_per_table: Este parâmetro identifica quantos arquivos de serão criados para cada tabela innodb, valor
padrão 1.
thread_cache_size: Quantidade de threads que são criadas na inicialização da instância.Este valor pode ser ajustado
dinamicamente.
tmp-table_size, max_heap_table_size: ambos precisam ser ajustados com o mesmo tamanho e previnem escrita em
disco. Ex:
tmp-table_size=1G
max_heap_table_size=1G
max_allowed_packet: valor máximo permitido por pacote, deve ser ajustado para o tamanho do maior pacote no
sistema. Um exemplo é setar 11 vezes o valor do seu maior arquivo BLOB.
83. Variaveis de replicação:
auto_increment_increment , auto_incremente_offset: utiliza as duas em conjunto quando utilizar replicação multi-master,
auto_incremente_offset deve receber um valor único para cada servidor e possui a função de não deixar gerar valores duplicados
em campos auto-increment.
binlog_format: Determina se a replicação é baseada em linha, statement ou ambos. Valor padrão: MIXED(> = MariaDB 10.2.4 )
STATEMENT(<= MariaDB 10.2.3 ).
slave_skip_erros: Quando um erro ocorre a replicação para, esta variável permite que uma lista de códigos de erro ignore e a replicação continue,
Usando all como uma opção permite que o slave continue replicando, independentemente do erro que ele encontre, muito cuidado ao aplicar essa
variável devido possibilidade de inconsistências na replicação.
sync_binlog: O MariaDB sincronizará seu arquivo de log binário com o disco após esses muitos eventos. O padrão é 0, caso em que o sistema
operacional lida com a descarga do arquivo no disco. 1 é a escolha mais segura, mas mais lenta, uma vez que o arquivo é descarregado após cada
gravação. Se o autocommit estiver habilitado, há uma gravação por declaração, caso contrário, há uma gravação por transação.
Mais informações:
https://mariadb.com/kb/en/library/replication-and-binary-log-server-system-variables/
https://mariadb.com/kb/en/library/server-system-variables/
84. Referências
Bem Forta, MariaDB Crash Course, 2011 Ed. Pearson
MariaDB Knowledge Base em https: https://mariadb.com/kb/en/
MySQL 5.7 Reference Manual