sqlite本地存储用户账号密码
时间: 2023-07-15 13:12:24 浏览: 64
SQLite是一种轻型的关系型数据库管理系统,非常适合用于本地存储数据。你可以使用SQLite来存储用户的账号和密码。
以下是一个使用Python实现的例子:
首先,需要安装SQLite Python库:
```
pip install sqlite3
```
然后,创建一个SQLite数据库文件,并建立一个用户表:
```python
import sqlite3
conn = sqlite3.connect('user.db')
c = conn.cursor()
# Create table
c.execute('''CREATE TABLE users
(username text, password text)''')
# Save (commit) the changes
conn.commit()
# Close the connection
conn.close()
```
接下来,可以编写一个注册用户的函数:
```python
def register(username, password):
conn = sqlite3.connect('user.db')
c = conn.cursor()
# Check if username already exists
c.execute("SELECT username FROM users WHERE username=?", (username,))
result = c.fetchone()
if result:
print("Username already exists")
return False
# Insert new user
c.execute("INSERT INTO users VALUES (?, ?)", (username, password))
# Save (commit) the changes
conn.commit()
# Close the connection
conn.close()
print("User registered successfully")
return True
```
最后,可以编写一个验证用户登录的函数:
```python
def login(username, password):
conn = sqlite3.connect('user.db')
c = conn.cursor()
# Check if username and password match
c.execute("SELECT username FROM users WHERE username=? AND password=?", (username, password))
result = c.fetchone()
if result:
print("Login successful")
return True
else:
print("Invalid username or password")
return False
# Close the connection
conn.close()
```
以上就是一个简单的使用SQLite存储用户账号密码的例子。当然,这只是一个示例,实际应用中还需要考虑更多的安全性和数据持久化方面的问题。