I've written a script which creates a new database, a table within the database, insert some values into it and fetch the values in one go. The way I've created the script below to achieve what I just said seems not to be an ideal way as there are too many repetitions in there. To be specific this two functions create_database() and connect() are almost identical. Moreover, I had to use mycursor = conn.cursor() twice within main function.
import mysql.connector
def create_database():
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd = "",
database=""
)
return mydb
def connect(databasename):
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd = "",
database=databasename
)
return mydb
def store_data(item_name,item_link):
mycursor.execute("INSERT INTO webdata (item_name,item_link) VALUES (%s,%s)", (item_name,item_link))
conn.commit()
if __name__ == '__main__':
db_name = "newdatabase"
conn = create_database()
mycursor = conn.cursor()
try:
mycursor.execute(f"CREATE DATABASE {db_name}")
except mysql.connector.errors.DatabaseError:
pass
conn = connect(db_name)
mycursor = conn.cursor()
mycursor.execute("DROP TABLE if exists webdata")
mycursor.execute("CREATE TABLE if not exists webdata (item_name VARCHAR(255), item_link VARCHAR(255))")
store_data("all questions","https://stackoverflow.com/questions/tagged/web-scraping")
mycursor.execute("SELECT * FROM webdata")
for item in mycursor.fetchall():
print(item)
What it prints (expected result):
('all questions', 'https://stackoverflow.com/questions/tagged/web-scraping')