{"id":1786,"date":"2024-09-16T16:00:00","date_gmt":"2024-09-16T10:30:00","guid":{"rendered":"https:\/\/geekpython.in\/?p=1786"},"modified":"2024-09-14T16:54:59","modified_gmt":"2024-09-14T11:24:59","slug":"connect-database-with-python","status":"publish","type":"post","link":"https:\/\/geekpython.in\/connect-database-with-python","title":{"rendered":"How To Connect Database With Python"},"content":{"rendered":"\n<p>In this article, we\u2019ll learn how to connect <strong>MySQL database<\/strong> with <strong>Python<\/strong> using the <strong>PyMySQL<\/strong> database driver.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Connect Database with Python<\/h1>\n\n\n\n<p>First, we need to install a MySQL database driver called <strong>PyMySQL<\/strong> that will help us bridge Python and MySQL.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:ps decode:true \" >pip install PyMySQL<\/pre><\/div>\n\n\n\n<p>Now, after installing this package, we can start the connection process by importing it into our Python script.<\/p>\n\n\n\n<p>Create a Python file, let\u2019s say <strong>db_connection.py<\/strong>, and write the following code.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" >import pymysql\n\n# Establish MySQL connection with Python\nsql_connection = pymysql.connect(\n    host=\"localhost\",\n    user=\"root\",\n    password=\"xxxxxxxxx\",\n    database=\"consumer\",\n    cursorclass=pymysql.cursors.DictCursor\n)\n\nprint(\"Connected to database.\")\n\n# Create cursor to interact with database\ncursor = sql_connection.cursor()\n\n# Create an entry in the database\ncursor.execute(\n      \"\"\"INSERT INTO consumers (name, address, phone)\n      values ('Max', '21 St. Parkway', 871231);\"\"\"\n)\n\n# Save the changes in the database\nsql_connection.commit()\n\n# Fetch data from the database\ncursor.execute(\n      \"\"\"SELECT * FROM consumers;\"\"\"\n)\n\ndata = cursor.fetchall()\nprint(data[0])\n\n# Close the connection with database\nsql_connection.close()\n\nprint(\"Operation successful.\")<\/pre><\/div>\n\n\n\n<p>This code creates a connection to the MySQL database and then writes an entry in the database table.<\/p>\n\n\n\n<p>First, the package is imported which will help us bridge Python and MySQL using Python code.<\/p>\n\n\n\n<p>Next, we established a connection using <code>pymysql.connect()<\/code> and passed the required arguments:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>hostname<\/code>: The location of the MySQL database. We have a MySQL server in the local system hence, we passed <code>\"localhost\"<\/code>.<\/li>\n\n\n\n<li><code>user<\/code>: Username of the MySQL server. In this case, we passed <code>\"root\"<\/code>, which is a default name.<\/li>\n\n\n\n<li><code>password<\/code>: Password of the MySQL server.<\/li>\n\n\n\n<li><code>database<\/code>: The name of the database with which you want to connect. In this case, we are connecting to the <code>\"consumer\"<\/code> database on the server.<\/li>\n\n\n\n<li><code>cursorclass<\/code>: This decides the format of the result returned by the cursor. In this case, the cursor will return results in a dictionary (<code>DictCursor<\/code>) format.<\/li>\n<\/ul>\n\n\n\n<p>Then we created a cursor (<code>sql_connection.cursor()<\/code>) object that helps in executing SQL queries.<\/p>\n\n\n\n<p>Using <code>cursor.execute()<\/code>, we executed an SQL query to insert an entry in the <code>consumers<\/code> table of the <code>consumer<\/code> database.<\/p>\n\n\n\n<p>Then we saved the changes to the database using <code>sql_connection.commit()<\/code>.<\/p>\n\n\n\n<p>We then executed an SQL query to get all the data from the <code>consumers<\/code> table in the database.<\/p>\n\n\n\n<p>Using <code>cursor.fetchall()<\/code>, we fetched all the entries from the table and printed the first result.<\/p>\n\n\n\n<p>Finally, we closed the connection with the database using <code>sql_connection.close()<\/code>.<\/p>\n\n\n\n<p>Now, when we run this code, we\u2019ll get the following result.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:tex mark:2 decode:true \" >Connected to database.\n{'name': 'Max', 'address': '21 St. Parkway', 'phone': 871231}\nOperation successful.<\/pre><\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><strong>That\u2019s all for now.<\/strong><\/p>\n\n\n\n<p><strong>Keep Coding\u270c\u270c.<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we\u2019ll learn how to connect MySQL database with Python using the PyMySQL database driver. Connect Database with Python First, we need to install a MySQL database driver called PyMySQL that will help us bridge Python and MySQL. Now, after installing this package, we can start the connection process by importing it into [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":1788,"comment_status":"closed","ping_status":"closed","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":[37,2],"tags":[38,39,31],"class_list":["post-1786","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-database","category-python","tag-database","tag-mysql","tag-python3","entry","has-media"],"_links":{"self":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1786","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=1786"}],"version-history":[{"count":1,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1786\/revisions"}],"predecessor-version":[{"id":1787,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1786\/revisions\/1787"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media\/1788"}],"wp:attachment":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media?parent=1786"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/categories?post=1786"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/tags?post=1786"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}