Hướng dẫn how do you display data from a database in python? - làm cách nào để hiển thị dữ liệu từ cơ sở dữ liệu trong python?

Trong bài viết này, bạn sẽ tìm hiểu mã rất đơn giản để tìm nạp dữ liệu từ cơ sở dữ liệu MySQL và hiển thị nó trong bảng HTML bằng ngôn ngữ lập trình Python.MySQL database and display it in an HTML table using Python programming language.

MySQL là hệ thống quản lý cơ sở dữ liệu quan hệ nguồn mở phổ biến và được sử dụng rộng rãi nhất. Nó có thể chạy trên nhiều nền tảng khác nhau mà không bị lỗi, ngay cả trên PC công suất thấp và Python cung cấp hỗ trợ để làm việc với cơ sở dữ liệu MySQL. Lập trình trong Python đơn giản hơn đáng kể và hiệu quả hơn so với các ngôn ngữ khác. Nó có một bộ thư viện và gói hữu ích giúp giảm thiểu việc sử dụng mã trong cuộc sống hàng ngày của chúng tôi. Python cần một trình điều khiển MySQL để truy cập cơ sở dữ liệu MySQL. Python cung cấp các mô -đun khác nhau để truy cập cơ sở dữ liệu MySQL từ một máy chủ web như PYMYSQL, MySQL.Connector, v.v. is the most popular and widely used Open Source Relational Database Management System. It can run on many different platforms without failure, even on a low-powered PC, and Python provides support to work with the MySQL database. Programming in Python is considerably simpler and more efficient compared to other languages. It has a set of useful libraries and packages that minimise the use of code in our day-to-day life. Python needs a MySQL driver to access the MySQL database. Python provides various modules to access MySQL databases from a web server such as PyMySQL, mysql.connector, etc.

Trong bài viết này, chúng tôi đã sử dụng mô -đun kết nối MySQL. Mô-đun kết nối MySQL được viết bằng Pure Python và tương thích với Python 3. Việc thực thi các truy vấn cơ sở dữ liệu thông qua Python là tự túc thông qua Python.MySQL Connector module is written in pure Python and is compatible with Python 3. It is self-sufficient to execute database queries through Python.

Cơ sở dữ liệu MySQL

Giả sử chúng ta có một bảng "nhân viên" có chứa ID nhân viên, tên, email và số điện thoại. Chúng tôi muốn hiển thị toàn bộ thông tin của nhân viên trên một trang web trong bảng HTML.employee" table that contains an employee id, name, email, and phone number. We want to display the employee's whole information on a web page in an HTML table.

CREATE TABLE IF NOT EXISTS `employee` (
  `emp_id` int(11) NOT NULL AUTO_INCREMENT,
  `emp_name` varchar(150) NOT NULL,
  `email` varchar(150) NOT NULL,
  `phone` varchar(100) NOT NULL,
  PRIMARY KEY (`emp_id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

INSERT INTO `employee` (`emp_id`, `emp_name`, `email`, `phone`) VALUES
(1, 'John', This email address is being protected from spambots. You need JavaScript enabled to view it.', '2323234543'),
(2, 'Smith', This email address is being protected from spambots. You need JavaScript enabled to view it.', '9898577442'),
(3, 'Priska', This email address is being protected from spambots. You need JavaScript enabled to view it.', '9393452387'),
(4, 'Gaga', This email address is being protected from spambots. You need JavaScript enabled to view it.', '8482764537');

Từng bước xử lý để tìm nạp dữ liệu từ MySQL

Chúng tôi cần hai mô -đun cho ứng dụng này, Webbrowser và MySQL.Connector. Mô -đun Webbrowser theo mặc định có sẵn với gói Python. Chúng tôi không cần cài đặt điều này, nhưng chúng tôi cần cài đặt mô -đun MySQL.Connector.webbrowser and mysql.connector. The webbrowser module is by default available with the python package. We do not need to install this, but we need to install the mysql.connector module.

Trình cài đặt Python MySQL

Trình cài đặt yêu cầu 'python.exe' trong đường dẫn hệ thống của bạn, nếu không nó sẽ không cài đặt được. Vì vậy, hãy chắc chắn để thêm Python trong môi trường hệ thống của bạn. Chúng tôi cũng có thể cài đặt Trình kết nối MySQL bằng lệnh PIP.python.exe' in your system PATH, otherwise it will fail to install. So make sure to add Python in your system environment. We can also install MySQL Connector using the pip command.

pip install mysql-connector

Như, đầu nối này đã được cài đặt trong hệ thống của tôi. Nó trả về sau-

c:\python37\Scripts>pip install mysql-connector
Requirement already satisfied: mysql-connector in c:\python37\lib\site-packages (2.2.9)

Đây cũng là một cách để kiểm tra cài đặt thành công của đầu nối MySQL.

Nhập các mô -đun

Đầu tiên, chúng ta cần nhập cả hai mô -đun ở đầu tập lệnh -

import mysql.connector
import webbrowser

Python kết nối với mysql

Tiếp theo, sử dụng hàm tạo Connect () để tạo kết nối với máy chủ MySQL. Đảm bảo thay thế 'tên máy chủ', 'tên người dùng', 'mật khẩu' và 'cơ sở dữ liệu' bằng thông tin và tên cơ sở dữ liệu của bạn.connect() constructor to create a connection to the MySQL server. Make sure to replace 'hostname', 'username', 'password' and 'database' with your database credentials and name.

conn = mysql.connector.connect(user='root', password='',
                              host='localhost',database='company')

if conn:
    print ("Connected Successfully")
else:
    print ("Connection Not Established")

Python MySQL tìm nạp dữ liệu và lưu trữ trong một biến

Ở đây, chúng tôi đã sử dụng truy vấn chọn để tìm nạp dữ liệu. Tiếp theo, chúng tôi đã lặp lại trên dữ liệu được tìm nạp và lưu trữ nó trong một biến danh sách theo định dạng bảng HTML.

select_employee = """SELECT * FROM employee"""
cursor = conn.cursor()
cursor.execute(select_employee)
result = cursor.fetchall()

p = []

tbl = "IDNameEmailPhone"
p.append(tbl)

for row in result:
    a = "%s"%row[0]
    p.append(a)
    b = "%s"%row[1]
    p.append(b)
    c = "%s"%row[2]
    p.append(c)
    d = "%s"%row[3]
    p.append(d)

Tạo mẫu HTML

Tiếp theo, chúng tôi đã tạo một mẫu HTML và vượt qua biến danh sách trên.

contents = '''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html; charset=ISO-8859-1"
http-equiv="content-type">
<title>Python Webbrowser</title>
</head>
<body>
<table>
%s
</table>
</body>
</html>
'''%(p)

Mở trình duyệt web

Mô -đun Python Webbrowser cung cấp một tính năng để mở một trang web trong trình duyệt. Trong mã đã cho, chúng tôi đã tạo một tệp HTML và đặt nội dung HTML được tạo ở trên trong đó, hiển thị nó trong trình duyệt web.webbrowser module provides a feature to open a webpage in the browser. In the given code, we have created an HTML file and placed the above generated HTML content in it, rendering it in a web browser.

filename = 'webbrowser.html'

def main(contents, filename):
    output = open(filename,"w")
    output.write(contents)
    output.close()

main(contents, filename)    
webbrowser.open(filename)

Hoàn thành mã để hiển thị dữ liệu MySQL trong bảng HTML bằng Python

Ở trên, chúng tôi đã giải thích mã trong các khối. Ở đây chúng tôi đã hợp nhất tất cả chúng lại với nhau để lấy mã hoàn chỉnh để hiển thị dữ liệu MySQL trong bảng HTML bằng Python.

import mysql.connector
import webbrowser

conn = mysql.connector.connect(user='root', password='',
                              host='localhost',database='company')

if conn:
    print ("Connected Successfully")
else:
    print ("Connection Not Established")

select_employee = """SELECT * FROM employee"""
cursor = conn.cursor()
cursor.execute(select_employee)
result = cursor.fetchall()

p = []

tbl = "<tr><td>ID</td><td>Name</td><td>Email</td><td>Phone</td></tr>"
p.append(tbl)

for row in result:
    a = "<tr><td>%s</td>"%row[0]
    p.append(a)
    b = "<td>%s</td>"%row[1]
    p.append(b)
    c = "<td>%s</td>"%row[2]
    p.append(c)
    d = "<td>%s</td></tr>"%row[3]
    p.append(d)


contents = '''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html; charset=ISO-8859-1"
http-equiv="content-type">
<title>Python Webbrowser</title>
</head>
<body>
<table>
%s
</table>
</body>
</html>
'''%(p)

filename = 'webbrowser.html'

def main(contents, filename):
    output = open(filename,"w")
    output.write(contents)
    output.close()

main(contents, filename)    
webbrowser.open(filename)

if(conn.is_connected()):
    cursor.close()
    conn.close()
    print("MySQL connection is closed.")    

Khi bạn chạy mã trên, nó sẽ trả về một cái gì đó như thế này trong trình duyệt.

Hướng dẫn how do you display data from a database in python? - làm cách nào để hiển thị dữ liệu từ cơ sở dữ liệu trong python?

Những bài viết liên quan

Làm thế nào để bạn hiển thị dữ liệu từ cơ sở dữ liệu trong GUI Python?

Chúng tôi sẽ sử dụng một thành phần nhập Tkinter để hiển thị từng dữ liệu trong cửa sổ. Trong biến này, sinh viên là một tuple và nó chứa một hàng dữ liệu. Chúng tôi đã sử dụng biến I làm chỉ mục cho mỗi hàng và biến J làm mỗi cột dữ liệu. Mã đầy đủ ở đây, thay đổi tên người dùng, mật khẩu và cơ sở dữ liệu của cơ sở dữ liệu MySQL của bạn.use one tkinter entry component to display each data in the window. In this variable student is a tuple and it contains one row of data. We used variable i as index for each row and variable j as each column of data. The full code is here , Change the userid,password and database name of your MySQL database.

Làm thế nào để bạn truy cập và hiển thị dữ liệu trong Python?

Trong đó mệnh đề sử dụng Python..
Nhập MySQL. Gói đầu nối ..
Tạo một đối tượng kết nối bằng MySQL. kết nối. ....
Tạo một đối tượng con trỏ bằng cách gọi phương thức con trỏ () trên đối tượng kết nối được tạo ở trên ..
Sau đó, thực thi câu lệnh CHỌN với mệnh đề WHERE, bằng cách chuyển nó dưới dạng tham số cho phương thức thực thi () ..

Làm cách nào để hiển thị dữ liệu MySQL trong Python?

Bạn có thể tìm nạp dữ liệu từ MySQL bằng phương thức Fetch () được cung cấp bởi MySQL-ConneNector-Python.Con trỏ.Lớp mysqlcursor cung cấp ba phương thức là fetchall (), fetchmany () và, fetchone () trong đó, phương thức fetchall () lấy tất cả các hàng trong tập hợp của một truy vấn và trả về chúng như danh sách các bộ dữ liệu.using the fetch() method provided by the mysql-connector-python. The cursor. MySQLCursor class provides three methods namely fetchall(), fetchmany() and, fetchone() where, The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples.

Làm thế nào tìm nạp dữ liệu từ cơ sở dữ liệu trong Python và hiển thị trong HTML?

Trình kết nối nhập Webbrowser Conn = MySQL.kết nối.Kết nối (user = 'root', password = '', host = 'localhost', database = 'company') nếu Conn: in ("kết nối thành công")Chọn * từ nhân viên "" "Trình con trỏ = Conn.con trỏ () con trỏ.