· 4 years ago · Jul 10, 2021, 06:32 PM
1import mysql.connector
2import time
3
4MySQL_Host = "localhost"
5MySQL_User = "root"
6MySQL_Pass = ""
7MySQL_DB = "newtable"
8
9try:
10 con = mysql.connector.connect(host=MySQL_Host,
11 user=MySQL_User,
12 password=MySQL_Pass,
13 database=MySQL_DB)
14 print("Establishing Connection to Database....")
15 time.sleep(4)
16except mysql.connector.Error as con_error:
17 print("Connection Lost: Something Went Wrong!")
18 print(con_error)
19
20
21# if connected
22print("Connection Established to Database.")
23time.sleep(2)
24
25dbcursor = con.cursor()
26
27#create table if not exists in database(newtable)
28table_fields = "CREATE TABLE IF NOT EXISTS accounts (\
29 id int(11),\
30 name varchar(255),\
31 email varchar(255)\
32 )"
33dbcursor.execute(table_fields)
34
35#imsert data into accounts table
36insert_data = "INSERT INTO accounts (id,name,email) VALUES (%s, %s, %s)"
37
38#single data entry in tuple
39#insert_data_value = (1, 'Arivu', 'random@gmail.com')
40#dbcursor.execute(insert_data, insert_data_value)
41
42#multiple data entries are wrapped in a List of tuples
43insert_data_values = [
44 (1, 'Arivu', 'random@gmail.com'),
45 (2, 'Zaya', 'random2@yahoo.in'),
46 (3, 'Kishan', 'cjxKish@gmail.com'),
47 (4, 'Raaj', 'raajk@hotmail.com')
48 ]
49#for single data entry, use .execute, for multiple data entry use executemany
50dbcursor.executemany(insert_data, insert_data_values)
51
52#it's necessary to use .commit because this makes changes to the table
53# by using con
54con.commit()
55time.sleep(2)
56print(f"MySQL Log: Inserted '{dbcursor.rowcount}' rows")