Featured Post

Python map() and lambda() Use Cases and Examples

Image
 In Python, map() and lambda functions are often used together for functional programming. Here are some examples to illustrate how they work. Python map and lambda top use cases 1. Using map() with lambda The map() function applies a given function to all items in an iterable (like a list) and returns a map object (which can be converted to a list). Example: Doubling Numbers numbers = [ 1 , 2 , 3 , 4 , 5 ] doubled = list ( map ( lambda x: x * 2 , numbers)) print (doubled) # Output: [2, 4, 6, 8, 10] 2. Using map() to Convert Data Types Example: Converting Strings to Integers string_numbers = [ "1" , "2" , "3" , "4" , "5" ] integers = list ( map ( lambda x: int (x), string_numbers)) print (integers) # Output: [1, 2, 3, 4, 5] 3. Using map() with Multiple Iterables You can also use map() with more than one iterable. The lambda function can take multiple arguments. Example: Adding Two Lists Element-wise list1 = [ 1 , 2 , 3 ]

How to Call SQL Query from Python

Python's top supported database is MySQL. You can run SQL queries from Python. Here're best examples of how to connect to MYSQL and access MYSQL tables from Python.


Read: How to Print String in Next Line Easily


Here are Steps

  1. Import MySQL connecter
  2. Give user id, password details
  3. Issue SQL query


Python Logic to import MySQL connector


import mysql.connector


Note: If the MySQL connecter not installed in python, you need to install it using the below command.


pip3 install mysql-connector-python --allow-external mysql-connector-python


How to Call SQL Query from Python



Supply user id and Password


conn=mysql.connector.connect(user='root', password='password', host='localhost', database='sakila')



mycursor=conn.cursor()


Issue SQL Query



mycursor.execute("show tables") # you won't see any result. You need to give print.


print(mycursor.fetchall())


mycursor.execute("select * from customer") # you won't see any result. You need to give print.


print(mycursor.fetchall())


This way you can issue SQL queries in Python.


Read: Top 100 Hadoop Interview Questions 1 of 4

Comments

Popular posts from this blog

How to Fix datetime Import Error in Python Quickly

SQL Query: 3 Methods for Calculating Cumulative SUM

Python placeholder '_' Perfect Way to Use it