{"id":1703,"date":"2024-04-03T16:25:25","date_gmt":"2024-04-03T10:55:25","guid":{"rendered":"https:\/\/geekpython.in\/?p=1703"},"modified":"2024-04-03T16:25:27","modified_gmt":"2024-04-03T10:55:27","slug":"mysql-database-in-python","status":"publish","type":"post","link":"https:\/\/geekpython.in\/mysql-database-in-python","title":{"rendered":"Create and Interact with MySQL Database in Python"},"content":{"rendered":"\n<p>Databases are crucial for storing and managing data. In this article, you&#8217;ll learn to create and interact with MySQL database in Python.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Installing PyMySQL<\/h2>\n\n\n\n<p><a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/pymysql.readthedocs.io\/en\/latest\/index.html\"><strong>PyMySQL<\/strong><\/a> is a MySQL client library written in Python that allows you to create and interact with MySQL databases.<\/p>\n\n\n\n<p>This is a third-party library, therefore you must install it on your system. To install it using <code>pip<\/code>, run one of the following commands in your terminal.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:sh decode:true \" >pip install pymysql\n\n--------------------- OR ---------------------\n\npython -m pip install pymysql<\/pre><\/div>\n\n\n\n<p><strong>Note: You must have a MySQL server installed in your system.<\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Creating MySQL Database<\/h2>\n\n\n\n<p>To begin, import the <strong>PyMySQL<\/strong> library into your project&#8217;s environment to handle database operations.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" ># Importing the required lib\nimport pymysql<\/pre><\/div>\n\n\n\n<p>PyMySQL includes a <code>connect()<\/code> function that accepts the necessary arguments, such as <strong>host<\/strong>, <strong>username<\/strong>, <strong>password<\/strong>, <strong>database name<\/strong>, and so on, to establish a connection with the database server.<\/p>\n\n\n\n<p>In this step, you will need access to your MySQL server&#8217;s username and password.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python mark:3-5 decode:true \" ># Initialize connection with server\nmysql_db = pymysql.connect(\n    host=\"localhost\",\n    user=\"root\",\n    password=\"********\"\n)<\/pre><\/div>\n\n\n\n<p>In the above code, the <code>host<\/code> is where your MySQL server is hosted; in this case, it is hosted on a local machine, therefore the value <code>\"localhost\"<\/code> is provided.<\/p>\n\n\n\n<p>The <code>user<\/code> is your MySQL server&#8217;s username, which is <code>\"root\"<\/code> by default, and the <code>password<\/code> is the one you specified when you first set up the server.<\/p>\n\n\n\n<p>To interact with the MySQL database, you must first create a cursor object for it using the <code>cursor()<\/code> function.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" ># Database cursor\ncursor = mysql_db.cursor()<\/pre><\/div>\n\n\n\n<p>This step involves running a MySQL query to create a database on the MySQL server using the cursor (<code>mysql_db.cursor()<\/code>) object.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" ># SQL query to create database\ncursor.execute(\"CREATE DATABASE IF NOT EXISTS pokemon_db\")\ncursor.execute(\"SHOW DATABASES\")<\/pre><\/div>\n\n\n\n<p>The <code>cursor.execute()<\/code> executes the SQL query. The first query says &#8220;Create a database named pokemon_db if it doesn&#8217;t exist already&#8221; and the second query says &#8220;Show all the databases reside on the server&#8221;.<\/p>\n\n\n\n<p>Finally, disconnect the database connection and cursor object with the <code>close()<\/code> function.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" ># Closing the database cursor and connection\ncursor.close()\nmysql_db.close()<\/pre><\/div>\n\n\n\n<p>When you run the code, nothing will appear on the console, but your database has been created on the server. You can check in the MySQL Workbench.<\/p>\n\n\n\n<p>To display all of the databases on the server using Python, add the following code to the script.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" ># Displaying databases\nfor databases in cursor:\n    print(databases)<\/pre><\/div>\n\n\n\n<p>Now, when you rerun the code, you&#8217;ll see all the databases residing on the server are displayed on the console.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:tex mark:5 decode:true \" >('books_db',)\n('information_schema',)\n('mysql',)\n('performance_schema',)\n('pokemon_db',)\n('sys',)<\/pre><\/div>\n\n\n\n<p>You can see your newly created database (<code>pokemon_db<\/code>) is being displayed.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Interacting with Database<\/h2>\n\n\n\n<p>You may simply interact with this newly generated MySQL database by adding tables and columns and performing CRUD operations.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Creating a Database Table<\/h3>\n\n\n\n<p>You have established a MySQL database called <code>pokemon_db<\/code>. Now you must create a table with some fields to store data related to the fields.<\/p>\n\n\n\n<p>Create a new file in your project directory and place the following code within it.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python mark:9-10 decode:true \" ># Importing PyMySQL and cursors\nimport pymysql.cursors\n\n# Initialize connection with database\nmysql_db = pymysql.connect(\n    host=\"localhost\",\n    user=\"root\",\n    password=\"********\",\n    database=\"pokemon_db\",\n    cursorclass=pymysql.cursors.DictCursor\n)\n\n# Database cursor\ncursor = mysql_db.cursor()\n\n# Function to create a table\ndef create_db_table():\n    cursor.execute('''\n                CREATE TABLE IF NOT EXISTS pokemon (\n                    id INT AUTO_INCREMENT PRIMARY KEY,\n                    name VARCHAR(500) NOT NULL UNIQUE,\n                    cp INT(50) NOT NULL,\n                    hp INT(50) NOT NULL\n                )\n            ''')\n    mysql_db.commit()\n\nif __name__ == \"__main__\":\n    create_db_table()\n\ncursor.close()<\/pre><\/div>\n\n\n\n<p>This time, the database name (<code>pokemon_db<\/code>) is supplied in the <code>connect()<\/code> function. This implies that a connection will be established to the <code>pokemon_db<\/code> database.<\/p>\n\n\n\n<p>The <code>cursorclass<\/code> is set to <code>cursors.DictCursor<\/code>, a cursor that returns results in a dictionary format.<\/p>\n\n\n\n<p>The <code>create_db_table()<\/code> function creates a table named <code>\"pokemon\"<\/code> containing the following fields:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>id<\/code>: This field assigns a serial number for each entry made in the database automatically due to <code>\"AUTO_INCREMENT\"<\/code>.<\/li>\n\n\n\n<li><code>name<\/code>: stores the Pokemon name.<\/li>\n\n\n\n<li><code>cp<\/code>: stores the combat power of the Pokemon.<\/li>\n\n\n\n<li><code>hp<\/code>: stores the high power of the Pokemon.<\/li>\n<\/ul>\n\n\n\n<p>The changes are saved to the database using <code>mysql_db.commit()<\/code>. After running the code, the table will be created with the specified fields.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Adding Data to the Database<\/h3>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" >...\n\n# Adding data to the database\ndef add_entry():\n    # SQL query\n    query = '''\n            INSERT INTO `pokemon` (`name`, `cp`, `hp`) \n            VALUES (%s, %s, %s)\n            '''\n    \n    # Adding three entries\n    cursor.execute(query, ('Charizard', 120, 200))\n    cursor.execute(query, ('Pikachu', 60, 100))\n    cursor.execute(query, ('Squirtle', 78, 102))\n    \n    # Committing the changes\n    mysql_db.commit()\n\nif __name__ == \"__main__\":\n    # create_db_table()\n    add_entry()\n\ncursor.close()<\/pre><\/div>\n\n\n\n<p>The <code>add_entry()<\/code> function is defined and added to the code from the previous section.<\/p>\n\n\n\n<p>Inside the function, an SQL query is defined to insert data in the <code>pokemon<\/code> table to the corresponding fields. Next, the function executes the SQL query multiple times, each time with different values for the Pokemon&#8217;s name, combat power (<code>cp<\/code>), and high power (<code>hp<\/code>).<\/p>\n\n\n\n<p>After adding the entries, the function commits the changes to the database using <code>mysql_db.commit()<\/code>.<\/p>\n\n\n\n<p>When you run the function, the data will be added to the database.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Reading Data from the Database<\/h3>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" >...\n\n# Reading data from the database\ndef read_entry():\n    # SQL query\n    query = '''\n    SELECT `name`, `cp`, `hp` FROM `pokemon`;\n    '''\n    cursor.execute(query)\n\n    # Fetching data from the database\n    for data in cursor.fetchall():\n        print(\n            data['name'],\n            data['cp'],\n            data['hp']\n        )\n\n\nif __name__ == \"__main__\":\n    # create_db_table()\n    # add_entry()\n    read_entry()\n\ncursor.close()<\/pre><\/div>\n\n\n\n<p>The <code>read_entry()<\/code> function executes an SQL query that selects all values from the table <code>pokemon<\/code>. The data is then fetched using the <code>cursor.fetchall()<\/code> function.<\/p>\n\n\n\n<p>You&#8217;ll get all the entries inserted into the database when you run the code.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:tex decode:true \" >Charizard 120 200\nPikachu 60 100\nSquirtle 78 102<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">Updating Data in the Database<\/h3>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" >...\n\n# Function to update an entry\ndef update_entry():\n    query = '''\n            UPDATE `pokemon`\n            SET `cp` = %s\n            WHERE `id` = %s\n            '''\n\n    # Executing SQL query with values\n    cursor.execute(query, (140, 2))\n\n    # Committing the changes\n    mysql_db.commit()\n\n\nif __name__ == \"__main__\":\n    # create_db_table()\n    # add_entry()\n    update_entry()\n    read_entry()\n\ncursor.close()<\/pre><\/div>\n\n\n\n<p>The <code>update_entry()<\/code> function is defined, and within it, an SQL query is written to update the <code>pokemon<\/code> table by setting the value for the <code>cp<\/code> field for the supplied <code>id<\/code>.<\/p>\n\n\n\n<p>The <code>cursor.execute()<\/code> function executes the query that updates the <code>cp<\/code> of the Pokemon to 140 whose <code>id<\/code> is equal to 2.<\/p>\n\n\n\n<p>The changes are then saved to the database using <code>mysql_db.commit()<\/code>. When you run the code, you&#8217;ll see the change in the value.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:tex mark:1 decode:true \" >Charizard 140 200\nPikachu 60 100\nSquirtle 78 102<\/pre><\/div>\n\n\n\n<p>You can see that the Charizard&#8217;s <code>cp<\/code> has been updated, and it is now 140 because it has an <code>id<\/code> of 2, which may differ in your situation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Deleting Data from the Database<\/h3>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" ># Function to delete the entry\ndef delete_entry():\n    query = '''\n            DELETE FROM `pokemon`\n            WHERE `id` = %s\n            '''\n\n    # Executing SQL query for deletion\n    cursor.execute(query, 2)\n    \n    # Committing the changes\n    mysql_db.commit()\n\n\nif __name__ == \"__main__\":\n    # create_db_table()\n    # add_entry()\n    # update_entry()\n    delete_entry()\n    read_entry()\n\n\ncursor.close()<\/pre><\/div>\n\n\n\n<p>The <code>delete_entry()<\/code> function executes an SQL query to remove the entire record from the <code>pokemon<\/code> table with the supplied <code>id<\/code>.<\/p>\n\n\n\n<p>When you run the code, you&#8217;ll see that the entire record of the id equal to 2 has been deleted.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:tex decode:true \" >Pikachu 60 100\nSquirtle 78 102<\/pre><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>You may work with MySQL databases in Python by using MySQL client libraries, and in this article, you&#8217;ve learned how to create and communicate with MySQL databases using the PyMySQL library.<\/p>\n\n\n\n<p>First, you learned to create a MySQL database using the PyMySQL library in Python.<\/p>\n\n\n\n<p>You interacted and performed the following operations after the database was established:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Created a MySQL database table<\/li>\n\n\n\n<li>Inserted the data into the database<\/li>\n\n\n\n<li>Reading that data from the database<\/li>\n\n\n\n<li>Updating the data in the database<\/li>\n\n\n\n<li>Deleting the data from the database<\/li>\n<\/ul>\n\n\n\n<p>There are various libraries available for building a MySQL database in Python, and the process of creating and communicating with the database is nearly identical to that described in this article.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\ud83c\udfc6<strong>Other articles you might be interested in if you liked this one<\/strong><\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/create-and-integrate-mysql-database-with-flask-app\">Create and integrate MySQL database in Flask app in Python<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/connect-sqlite-database-with-flask-app\">Create and connect SQLite database with Flask app<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/structure-flask-app-with-blueprint\">How to use Flask&#8217;s Blueprint to structure your Flask app much better<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/how-to-use-sessions-in-flask\">What are sessions and how to create a session in Flask<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/build-websocket-server-and-client-using-python\">Create a WebSocket server and client in Python<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/decorators-in-python\">How do decorators in Python work and how to create a custom decorator<\/a>?<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><strong>That&#8217;s all for now<\/strong><\/p>\n\n\n\n<p><strong>Keep Coding\u270c\u270c<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Databases are crucial for storing and managing data. In this article, you&#8217;ll learn to create and interact with MySQL database in Python. Installing PyMySQL PyMySQL is a MySQL client library written in Python that allows you to create and interact with MySQL databases. This is a third-party library, therefore you must install it on your [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":1706,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ocean_post_layout":"","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"","ocean_second_sidebar":"","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"","ocean_custom_header_template":"","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"","ocean_menu_typo_font_family":"","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"","ocean_post_oembed":"","ocean_post_self_hosted_media":"","ocean_post_video_embed":"","ocean_link_format":"","ocean_link_format_target":"self","ocean_quote_format":"","ocean_quote_format_link":"post","ocean_gallery_link_images":"on","ocean_gallery_id":[],"footnotes":""},"categories":[2,37],"tags":[38,39,12],"class_list":["post-1703","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","category-database","tag-database","tag-mysql","tag-python","entry","has-media"],"_links":{"self":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1703","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/comments?post=1703"}],"version-history":[{"count":4,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1703\/revisions"}],"predecessor-version":[{"id":1708,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1703\/revisions\/1708"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media\/1706"}],"wp:attachment":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media?parent=1703"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/categories?post=1703"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/tags?post=1703"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}