How to use MySQL and Python to develop a simple login function
In modern network application development, the login function is a very common and essential part. This article will introduce how to use the MySQL database and the Python programming language to develop a simple login function, and provide specific code examples.
First, we need to create a MySQL database to store the user's login information. You can use MySQL command line tools or graphical interface tools to operate.
Open the MySQL command line tool and enter the following command to create a database named user
:
CREATE DATABASE user;
Then switch to the user
database:
USE user;
Next, create a data table named login
to store the user’s login information. The structure of this data table includes three fields: id
, username
, and password
, which are used to store the user's unique ID, username, and password respectively. Enter the following command to create a data table:
CREATE TABLE login ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) NOT NULL, password VARCHAR(50) NOT NULL );
Next, we use the Python programming language to connect to the MySQL database and write code to implement the registration and login functions .
First, we need to install the mysql-connector-python
library to connect to the MySQL database. It can be installed using the following command:
pip install mysql-connector-python
Then, create a Python file named login.py
and enter the following code:
import mysql.connector # 连接到MySQL数据库 db = mysql.connector.connect( host="localhost", user="root", passwd="your_mysql_password", database="user" ) # 注册功能 def register(username, password): cursor = db.cursor() # 检查用户名是否已存在 cursor.execute("SELECT * FROM login WHERE username = %s", (username,)) result = cursor.fetchone() if result: print("该用户名已存在,请重新输入!") return False # 插入新用户的信息 sql = "INSERT INTO login (username, password) VALUES (%s, %s)" values = (username, password) cursor.execute(sql, values) db.commit() print("注册成功!") return True # 登录功能 def login(username, password): cursor = db.cursor() # 验证用户名和密码是否匹配 cursor.execute("SELECT * FROM login WHERE username = %s AND password = %s", (username, password)) result = cursor.fetchone() if result: print("登录成功!") return True else: print("用户名或密码错误,请重新输入!") return False # 调用注册和登录功能 register("user1", "password1") login("user1", "password1")
Please note that ## needs to be Replace #your_mysql_password with your own MySQL password.
login.py file. If everything goes well, you should see the output as successful registration and login success.
The above is the detailed content of How to develop a simple login function using MySQL and Python. For more information, please follow other related articles on the PHP Chinese website!