Connection to the Database
Create, Read, Update, Delete (CRUD) DATA
Create, Read, Update, Delete (CRUD) DATA
After confirming the link below, you have access to db4free.net's MySQL 8.0 database server. The host name to access the server is db4free.net and the port is 3306. You can use phpMyAdmin on our website to log in to the server.
Please use the following link to finish the registration process within the next 14 days. By clicking this link you confirm (again) that you understand that:
* db4free.net is a testing environment
* db4free.net is not suitable for production
* if you decide to use your db4free.net database in production despite the warnings, you do that at your own risk (very frequent backups are highly recommended)
* data loss and outages can happen at any time (any complaints about that will likely be ignored)
* the db4free.net team is not granting any warranty or liability of any kind
* the db4free.net team reserves the right to delete databases and/or accounts at any time without notice
* it is up to you to get the latest information from Twitter (https://twitter.com/db4free_net) and the db4free.net blog (https://www.mpopp.net/category/db4free/)
* db4free.net provides only a MySQL database, but no web space (there is nowhere to upload any files)
Further:
* db4free.net is a service for testing, not for hosting. Databases that store more than 200 MB data will be cleared at irregular intervals without notification
Open your replit account: https://replit.com/~
Create and choose Python
In main.py, please kindly copy and paste this:
from flask import Flask, render_template, url_for, redirect, request, session, flash
import mysql.connector
app = Flask(__name__)
app.secret_key = "asdfghjkl12345fdsa_fdsakld8rweodfds"
db = mysql.connector.connect(
host="remotemysql.com",
user="",
passwd="",
database=""
)
cursor = db.cursor()
if db.is_connected():
print("Berhasil terhubung ke database")
if __name__ == '__main__':
# Run the Flask app
#3306
app.run(host='0.0.0.0',debug=True, port=3306)
Install this pip in the shell:
pip install mysql-connector
pip install flask-mysql
Create database, table and columns the data. Visit this link:
https://remotemysql.com/databases.php?action=new
Open phpmyadmin(click here), then login. Choose sql. Copy and paste the following script:
CREATE DATABASE IF NOT EXISTS `YOUR_DATABASE` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `YOUR_DATABASE`;
CREATE TABLE IF NOT EXISTS `dosen`
(
dosen_id int NOT NULL AUTO_INCREMENT,
nama VARCHAR(50),
univ VARCHAR(50),
jurusan VARCHAR(50),
PRIMARY KEY(dosen_id)
);
INSERT INTO dosen (nama, univ, jurusan)
VALUES
("faqih","Telkom University", "Information System"),
("Aulia","Telkom University", "Informatics"),
("Ali","Brawijaya University", "Informatics");
Run the replit
There are 3 files important:
main.py
templates (folder). This is for html files only
static (folder). This is for CSS, JS and assets documentation
You can add the css file in the static folder by uploading this file (click here)
Prepare the template layout.html
This is for template:
{% block content %}
% endblock %}
Above is inside the following script:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" type=text/css href="{{ url_for('static', filename='bootstrap.min.css') }}">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
{% with messages = get_flashed_messages(with_categories=true) %}
<!-- Categories: success (green), info (blue), warning (yellow), danger (red) -->
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{{ category }} alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
{{ message }}
</div>
{% endfor %}
{% endif %}
{% endwith %}
{% block content %}
{% endblock %}
</div>
</div>
</div>
</body>
</html>
Create main webpage using index.html in folder templates
{% extends "layout.html" %}
{% block title %}Login Page{% endblock %}
{% block content %}
<h1 class="text-center">Welcome in the dashboard</h1>
<form action="{{ url_for('index') }}" method=post>
<div class="mb-13 mt-3">
<label for="email" class="form-label">Email:</label>
<input type="email" class="form-control" placeholder="Email" name="username" required autofocus>
</div>
<div class="mb-3">
<label for="pwd" class="form-label">Password:</label>
<input type="password" class="form-control" placeholder="Input password" name="password" required>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
{% endblock %}
Add @app.route('/') in main.py
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
if request.form['username'] != 'x@gmail.com' or request.form['password'] != 'x':
flash('Invalid username/password','danger')
else:
session['logged_in'] = True
flash('Login successful','success')
return redirect(url_for('dosen'))
return render_template('index.html')
Add @app.route('/logout') in main.py
@app.route('/logout')
def logout():
session.pop('logged_in', None)
flash('Logout successful','success')
return redirect(url_for('index'))
Read Data in database
Prepare route:
@app.route('/dosen')
def dosen():
cursor = db.cursor()
sql = "SELECT * FROM dosen"
cursor.execute(sql)
dosen = cursor.fetchall()
cursor.close()
return render_template('dosen.html', dosen=dosen)
Prepare dosen.html
{% extends "layout.html" %}
{% block title %}Dosen Page{% endblock %}
{% block content %}
{% if session.logged_in %}
<h3 class="one">Welcome Dosen</h3>
<a href="/dosen/tambah" class="btn btn-primary" role="button">Tambah dosen</a>
<a href="{{ url_for('logout') }}" class="btn btn-info" role="button">Logout</a>
<table class="table">
<thead>
<tr>
<th scope="col">ID Dosen</th>
<th scope="col">Nama Dosen</th>
<th scope="col">Universitas</th>
<th scope="col">Jurusan</th>
<th scope="col">Aksi</th>
</tr>
</thead>
<tbody>
{% for d in dosen %}
<tr>
<td>{{ d[0] }}</td>
<td>{{ d[1] }}</td>
<td>{{ d[2] }}</td>
<td>{{ d[3] }}</td>
<td>
<a href="/dosen/edit/{{ d[0] }}" class="btn btn-warning" role="button">Edit</a>
<a href="/dosen/delete/{{ d[0] }}" class="btn btn-danger" role="button" onclick="return confirm('Are you sure you want to delete?');">Delete</a></td>
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
{% endblock %}
Create Data in database
Prepare the file management:
templates/dosen/...
Prepare route:
@app.route('/dosen/tambah', methods=['GET', 'POST'])
def tambahdosen():
if request.method == 'GET':
return render_template('dosen/add.html')
else:
nama = request.form['nama']
univ = request.form['univ']
jurusan = request.form['jurusan']
cursor = db.cursor()
cursor.execute('''INSERT INTO dosen(nama,univ,jurusan) VALUES(%s,%s,%s)''',(nama,univ,jurusan))
db.commit()
cursor.close()
flash('Data added successfully','success')
return redirect(url_for('dosen'))
return render_template('dosen.html')
Prepare add.html:
{% extends "layout.html" %}
{% block title %}Tambah Dosen{% endblock %}
{% block content %}
<form action="/dosen/tambah" method=post>
<div class="mb-13 mt-3">
<label for="nama" class="form-label">Nama:</label>
<input type="input" class="form-control" placeholder="Nama" name="nama" required autofocus>
</div>
<div class="mb-3">
<label for="univ" class="form-label">Universitas:</label>
<input type="input" class="form-control" placeholder="Universitas" name="univ" required>
</div>
<div class="mb-3">
<label for="jurusan" class="form-label">Jurusan:</label>
<input type="input" class="form-control" placeholder="Jurusan" name="jurusan" required>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
{% endblock %}
Update Data in database
Prepare route:
@app.route('/dosen/edit/<int:id>', methods=['GET', 'POST'])
def editdosen(id):
if request.method == 'GET':
cursor = db.cursor()
cursor.execute('''
SELECT *
FROM dosen
WHERE dosen_id=%s''', (id, ))
dosen = cursor.fetchone()
cursor.close()
return render_template('dosen/edit.html', dosen=dosen)
else:
nama = request.form['nama']
univ = request.form['univ']
jurusan = request.form['jurusan']
cursor = db.cursor()
cursor.execute('''
UPDATE dosen
SET
nama = %s,
univ = %s,
jurusan = %s
WHERE
dosen_id = %s;
''',(nama,univ,jurusan,id))
db.commit()
cursor.close()
return redirect(url_for('dosen'))
return render_template('dosen.html')
Prepare edit.html:
{% extends "layout.html" %}
{% block title %}Edit Dosen{% endblock %}
{% block content %}
<form action="/dosen/edit/{{ dosen[0] }}" method=post>
<div class="mb-13 mt-3">
<label for="nama" class="form-label">Nama:</label>
<input type="input" class="form-control" placeholder="Nama" name="nama" value="{{ dosen[1] }}" required>
</div>
<div class="mb-3">
<label for="univ" class="form-label">Universitas:</label>
<input type="input" class="form-control" placeholder="Universitas" name="univ" value="{{ dosen[2] }}" required>
</div>
<div class="mb-3">
<label for="jurusan" class="form-label">Jurusan:</label>
<input type="input" class="form-control" placeholder="Jurusan" name="jurusan" value="{{ dosen[3] }}" required>
</div>
<button type="submit" class="btn btn-primary">Update</button>
</form>
{% endblock %}
Delete Data in database
Prepare route:
@app.route('/dosen/delete/<int:id>', methods=['GET'])
def deletedosen(id):
if request.method == 'GET':
cursor = db.cursor()
cursor.execute('''
DELETE
FROM dosen
WHERE dosen_id=%s''', (id, ))
db.commit()
cursor.close()
return redirect(url_for('dosen'))
return render_template('dosen.html')
Note:
This is in render_template
displaydata=cur.fetchall()
datadisplay = displaydata
This is in table <tbody>
{% for row datadisplay %}
<th scope="row"> {{ loop.index }}</th>
{% endfor %}
Created!
You have successfully created a new database. The details are below.
Username: wAffmdiOi7
Database name: wAffmdiOi7
Password: igBJz9WbOS
Server: remotemysql.com
Port: 3306
These are the username and password to log in to your database and phpMyAdmin
Make sure you keep your password secure. Ensure you keep back ups of your database in case it gets deleted.
Password Reset!
The password for the database 4kAcyOC7Ra has been reset.
The new password is 9fjhWFdih3