fork download
  1. import mysql.connector
  2. connection = mysql.connector.connect(host="localhost",user="root",password="root") #connection object to connect python with mysql
  3. print(connection)
  4. if connection.is_connected(): #print connection object memory address
  5. print("Python mysql connected") #check connection is established or not
  6. cursor = connection.cursor() #create cursor to activate pointer to execute commands
  7. cursor.execute("CREATE DATABASE PYMYSQL;") #run execute() function to execute queries
  8. cursor.execute("USE PYMYSQL;")
  9. cursor.execute("""CREATE TABLE STUDENTS
  10. (
  11. S_NAME CHAR(50),
  12. AGE INT
  13. );""")
  14. cursor.execute("INSERT INTO STUDENTS VALUES('KARAN',17);")
  15. cursor.execute("""INSERT INTO STUDENTS VALUES
  16. ("MAHMOOD",16),
  17. ("NITHIN",17);""")
  18. connection.commit() #commit function accept database and table creation and insert records into it.
  19. connection.close() #To close the connection
  20. else:
  21. print("Python mysql not connected")
  22.  
Success #stdin #stdout 0.02s 25280KB
stdin
Standard input is empty
stdout
import mysql.connector
connection = mysql.connector.connect(host="localhost",user="root",password="root")     #connection object to connect python with mysql
print(connection)							
if connection.is_connected():                                        #print connection object memory address
        print("Python mysql connected")                       #check connection is established or not
    	cursor = connection.cursor()                  #create cursor to activate pointer to execute commands
    	cursor.execute("CREATE DATABASE PYMYSQL;") #run execute() function to execute queries
    	cursor.execute("USE PYMYSQL;")          
    	cursor.execute("""CREATE TABLE STUDENTS
(
S_NAME CHAR(50),
AGE INT
);""")
    	cursor.execute("INSERT INTO STUDENTS VALUES('KARAN',17);")
    	cursor.execute("""INSERT INTO STUDENTS VALUES
("MAHMOOD",16),
("NITHIN",17);""")
    	connection.commit()          #commit function accept database and table creation and insert records into it.
    	connection.close()						     #To close the connection
else:
    	print("Python mysql not connected")