Example : Python-MySql Connectivity Code using Pycharm.
views.py         (Of already created inside Apps file)


   from django.shortcuts import render
   import pymysql     

   def connect(request):
       conn = pymysql.connect(host='localhost', user='root', passwd='', db='databasename')
       mycursor = conn.cursor()
       msg = "Database Connected..!!"
       print(msg)        # Message will displayed in pycharm terminal.
       
       mycursor.close()
       conn.close()

       return render(request, "UserReg.html",{'msg1': msg})   #Message will displayed on html 
          page.

-------------------------------------------------------------------------------
UserReg.html     (Of project template folder)


   <!DOCTYPE html>
      <html lang="en">
         <head>
            <meta charset="UTF-8">
            <title>Codershelpline</title>
         </head>
         <body>
            {{ msg1 }}
            <br>
            <br>
            This is connectivity page..!!
         </body>
     </html>

-------------------------------------------------------------------------------
urls.py          (Of/create inside Apps file)


  from django.urls import path
  from . import views

  urlpatterns = [
     path('connect', views.connect),  # Opens connect function of views.py file 
         using '/connect' at browser address bar.
     # path('', views.connect),   # Opens connect function of views.py file automatically 
         as default.
  ]

-------------------------------------------------------------------------------
urls.py          (Of already created inside project file)


  from django.urls import path, include  

  urlpatterns = [   
     path('', include('Appname.urls')),
  ]
-------------------------------------------------------------------------------

NB :
- pymysql must be installed.
- Mysql database must be created.

 157 total views,  1 views today

Categories: Python

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.