Hey my friends, a new post about this war. I don't know which is better, but I'll try to figure it out. I hope y'all enjoy this series. Here we go!
It's regular in the job environment to have to connect to databases in this case, we're going to connect with MySQL.
You only need to have to install MySQL server, in my case I had to create a database called onepiece and a table called crews, crews has 4 fields, id, name, ship, captain.
Python
First, you need to install a driver called "mysql-connector-python" this driver is to connect to the database and can find, insert, update and delete in this database. With this driver you can do a develop to save your data in MySQL.
python -m pip install mysql-connector-python
Here is the code of python, I'm going to add comments into language for explaining all methods or functions.
# Import driver for connecting to Mysql.
import mysql.connector
# It's not necessary, but It's a good way to show organized data.
from pprint import pprint
# Do you remember how to use the class? We have another example.
class CRUD():
# Method constructor, with 4 parameters, host: "IP of server mysql", user: "Database's user", password: "Database's password", database: "Database's name"
def __init__(self, host, user, password, database):
# A method for connecting to database.
self.mydb = mysql.connector.connect(
host=host,
user=user,
password=password,
database=database
)
# Method to create a new row.
def create(self, data):
# This is the string of syntax in the SQL language, "INSERT INTO table (fields) VALUES (%typeofdata)" is to say you want to add a new row. This way is a good practice for avoiding SQL injection.
sql = "INSERT INTO crews (name, ship, captain) VALUES (%s, %s, %s)"
# The initialize method of executing queries.
mycursor = self.mydb.cursor()
# Execute query and put together data. Data has to be in the same order that you want to put into the SQL query.
mycursor.execute(sql, data)
# Save data in database.
self.mydb.commit()
# Return id inserted.
return mycursor.lastrowid
# Method to find and print all rows from the table.
def find(self):
# This is the string of syntax in the SQL language, find all data into crews.
sql = "SELECT * FROM crews"
# The initialize method of executing queries.
mycursor = self.mydb.cursor()
# Execute query.
mycursor.execute(sql)
for result in mycursor.fetchall():
pprint(result)
# Method to find One row from the table.
def findOne(self, data):
# This the string of syntax in SQL language, find all data into crews where captian is equal to data recived.
sql = "SELECT * FROM crews WHERE captain = %s"
# The initialize method of executing queries.
mycursor = self.mydb.cursor()
# Execute query and put together data. Data has to be in the same order that you want to put into the SQL query.
mycursor.execute(sql, [data])
# Get only one coincidence.
myresult = mycursor.fetchone()
print('Find One')
return myresult
# Method to update One registry by Id.
def update(self, id, data):
# This is the string of syntax in the SQL language, "UPDATE table SET field = %typeofdata WHERE field = %typeofdata" is to say you want to update a row. This way is a good practice for avoiding SQL injection.
sql = "UPDATE crews SET name = %s, ship = %s, captain = %s WHERE id = %s"
# The initialize method of executing queries.
mycursor = self.mydb.cursor()
# In this case I get a list with id, I delete this register.
data.pop(0)
# This is a way for join two arrays.
val = data + [id]
# Execute query and put together data. Data has to be in the same order that you want to put into the SQL query.
mycursor.execute(sql, val)
# Save data in database.
self.mydb.commit()
# Return row count updated.
return mycursor.rowcount
# Method to delete One registry by Id.
def delete(self, id):
# This is the string of syntax in the SQL language, "DELETE FROM table WHERE id = %typeofdata" is to say you want to delete a row. This way is a good practice for avoiding SQL injection.
sql = "DELETE FROM crews WHERE id = %s"
# The initialize method of executing queries.
mycursor = self.mydb.cursor()
# Execute query and put together data. Data has to be in the same order that you want to put into the SQL query.
mycursor.execute(sql, [id])
# Save data in database.
self.mydb.commit()
# Return row count deleted.
return mycursor.rowcount
# Initialize class.
onepiece = CRUD("localhost", "root", "password", "onepiece")
# Find one register.
crew = onepiece.findOne("Luffy")
# Create one register.
id = onepiece.create(['Red-Haired Pirates',
'Red Force',
'Shanks'])
# Crew is a tuple, tuple is not editable, then I have to change to list.
crew = list(crew)
# Edit field that you want to update.
crew[2] = "Sunny"
# Update and print count of rows updated.
print(f"Updated documents: {onepiece.update(crew[0], crew)}")
# Print all registers from the table after the update.
onepiece.find()
# Delete and print count of rows deleted.
print(f"Deleted documents: {onepiece.delete(id)}")
# Print all registers from the table after deleting.
onepiece.find()
PHP
First, you need to install a driver called "php-mysql" this driver is to connect to the database and can find, insert, update and delete in this database. With this driver you can do a develop to save your data in MySQL.
apt install php-mysql
Here is the code of PHP, I'm going to add comments into language for explaining all methods or functions. Here, it's not necessary to import the driver because when you install php-mysql you can use the driver by default.
<?php
class CRUD
{
public function __construct($host, $user, $password, $database)
{
$this->mysqli = new mysqli($host, $user, $password, $database);
}
public function create($data)
{
$stmt = $this->mysqli->prepare("INSERT INTO crews (name, ship, captain) VALUES (?, ?, ?)");
$stmt->bind_param('sss', $data[0], $data[1], $data[2]);
$stmt->execute();
return $stmt->insert_id;
}
public function find()
{
echo "Find \n";
$res = $this->mysqli->query("SELECT * FROM crews");
if ($res) {
while ($row = $res->fetch_assoc()) {
var_dump($row);
}
}
}
public function findOne($data = '')
{
echo "Find One \n";
$stmt = $this->mysqli->prepare("SELECT * FROM crews WHERE captain = ?");
$stmt->bind_param('s', $data);
$stmt->execute();
$res = $stmt->get_result();
return $res->fetch_assoc();
}
public function update($id, $data)
{
unset($data['id']);
$stmt = $this->mysqli->prepare("UPDATE crews SET name = ?, ship = ?, captain = ? WHERE id = ?");
$stmt->bind_param('sssi', $data['name'], $data['ship'], $data['captain'], $id);
$stmt->execute();
return $stmt->affected_rows;
}
public function delete($id)
{
$stmt = $this->mysqli->prepare("DELETE FROM crews WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
return $stmt->affected_rows;
}
}
$onepiece = new CRUD("localhost", "root", "password", "onepiece");
$crew = $onepiece->findOne("Luffy");
$id = $onepiece->create([
'Red-Haired Pirates',
'Red Force',
'Shanks',
]);
$crew['ship'] = 'Sunny';
echo "Updated documents: " . $onepiece->update($crew['id'], $crew) . "\n";
$onepiece->find();
echo "Deleted documents: " . $onepiece->delete($id) . "\n";
$onepiece->find();
?>
Javascript
First, you need install a module called "mysql" this module is to connect to the database and can find, insert, update and delete in this database. With this module you can do a develop to save your data in MySQL.
For this example, I did all code with async/await method.
npm install mysql
Here is code of Javascript, I'm going to add comments into language for explaining all methods or functions.
const mysql = require('mysql');
const util = require('util');
class CRUD {
constructor(host, user, password, database) {
this.connection = mysql.createConnection({
host,
user,
password,
database
});
this.query = util.promisify(this.connection.query).bind(this.connection);
}
async create(data) {
const result = await this.query(
`INSERT INTO crews (name, ship, captain) VALUES (?,?,?)`,
data
);
return result.insertId;
}
async find() {
const rows = await this.query(`SELECT * FROM crews`);
console.log(rows);
}
async findOne(data = {}) {
const rows = await this.query(`SELECT * FROM crews WHERE captain = ?`, [
data
]);
return rows[0];
}
async update(id, data) {
delete data.id;
const result = await this.query(
`UPDATE crews SET name = ?, ship = ?, captain = ? WHERE id = ?`,
[...Object.values(data), id]
);
return result.affectedRows;
}
async delete(id) {
const result = await this.query(`DELETE FROM crews WHERE id = ?`, [id]);
return result.affectedRows;
}
}
const main = async () => {
const onepiece = new CRUD('localhost', 'root', 'password', 'onepiece');
const crew = await onepiece.findOne('Luffy');
const id = await onepiece.create([
'Red-Haired Pirates',
'Red Force',
'Shanks'
]);
crew.ship = 'Sunny';
console.log(
'Updated documents: ' + (await onepiece.update(crew.id, crew))
);
await onepiece.find();
console.log('Deleted documents: ' + (await onepiece.delete(id)));
await onepiece.find();
};
main();
Conclusion
Structure: Change a lot, because every modules/drivers are different.
Lines: Python: 68, PHP: 75, Javascript: 70
Easy to understand: For me It's more clear javascript, because you can add more fields without you have to make a big change.
Would you like that I write more info about mysql?
I hope you enjoy my post and remember that I am just a Dev like you!