Python+Mysql 7
Python+Mysql 7
a n u l t i m a t e g u i d e
A R U N A R U N I S T O
To use mysql using python you need to
install the library first, use the below code to
install the mysql-connector.
import mysql.connector
config = {
"user":"root",
'password':'arunisto',
'host':'localhost'
}
db = mysql.connector.connect(**config)
cursor = db.cursor()
config Dictionary:
Database Connection:
db = mysql.connector.connect(**config):
This line establishes a connection to the
MySQL server using the configuration
parameters provided in the config
dictionary.
**config uses dictionary unpacking to
pass the key-value pairs in config as
keyword arguments to the
mysql.connector.connect function.
Creating a Cursor:
Creating Database
db_name = 'sample_database'
cursor.execute(
f"CREATE DATABASE IF NOT EXISTS
{db_name} DEFAULT CHARACTER SET 'utf8'"
)
Database Creation Query:
cursor.execute(f"CREATE DATABASE IF
NOT EXISTS {db_name} DEFAULT
CHARACTER SET 'utf8'"): This line
executes an SQL query to create a
database with the name specified in the
db_name variable.
The IF NOT EXISTS clause ensures that
the database is only created if it doesn't
already exist.
DEFAULT CHARACTER SET 'utf8'
specifies the character set for the
database. In this case, it sets the
character set to UTF-8, which supports a
wide range of characters from various
languages.
Creating Tables
tables = {}
tables['logs'] = (
"CREATE TABLE `logs` ("
"`id` int(11) NOT NULL AUTO_INCREMENT,"
"`text` varchar(250) NOT NULL, "
"`user` varchar(250) NOT NULL, "
"`created` datetime NOT NULL DEFAULT
CURRENT_TIMESTAMP, "
"PRIMARY KEY (`id`)"
") ENGINE=InnoDB"
)
cursor.execute("USE {}".format(db_name))
try:
cursor.execute(tables['logs'])
except mysql.connector.Error as err:
if err.errno ==
errorcode.ER_TABLE_EXISTS_ERROR:
print("Table already exists")
else:
print(err.msg)
Defining a Table Schema:
cursor.execute("USE
{}".format(db_name)): This line switches
the MySQL connection to use the
database specified in the db_name
variable. It's important to select the
appropriate database before executing
table creation queries.
Handling Errors:
Updating data
sql = "UPDATE logs SET text = %s WHERE id =
%s"
values = ("text updated", 1)
cursor.execute(sql, values)
db.commit()
Deleting Data