注意:要想在python腳本中訪問mysql汗茄,必須不能使用mysql默認(rèn)的密碼番电,必須要手動修改下數(shù)據(jù)庫的密碼:
方法:
- 進(jìn)入到mysql中:
mysql -u root -p
回車
- 修改mysql密碼步驟:
(注意:一定要use mysql;)
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| myflaskapp |
| mysql |
| performance_schema |
| test |
+--------------------+
5 rows in set (0.01 sec)
mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> update user set password=password('test123') where user='root';
Query OK, 3 rows affected (0.06 sec)
Rows matched: 3 Changed: 3 Warnings: 0
3.配置數(shù)據(jù)庫代碼:
# from app import views
app = Flask(__name__)
# Config MySQL https://flask-mysqldb.readthedocs.io/en/latest/
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'test123'
app.config['MYSQL_DB'] = 'myflaskapp'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
# init MYSQL
mysql = MySQL(app)
'''
4.啟動服務(wù)器
if name=='main':
app.secret_key = 'test123'
app.run(debug=True)
5. 此時因?yàn)橐惨呀?jīng)寫好了連接mysql的代碼:
User Register
@app.route('/register', methods=['GET', 'POST'])
def register():
form = RegisterForm(request.form)
if request.method == 'POST' and form.validate():
name = form.name.data
email = form.email.data
username = form.username.data
password = sha256_crypt.encrypt(str(form.password.data))
# Create cursor
cur = mysql.connection.cursor()
# Execute query
cur.execute("INSERT INTO users(name, email, username, password) VALUES(%s, %s, %s, %s)", (name, email, username, password))
# Commit to DB
mysql.connection.commit()
# Close connection
cur.close()
flash('You are now registered and can log in', 'success')
return redirect(url_for('index'))
return render_template('register.html', form=form)
6. 在頁面上點(diǎn)擊Register撒强,會彈出來register.html頁面挽荡,然后在頁面行填寫合適的信息后倦零,點(diǎn)擊submmit误续,mysql數(shù)據(jù)庫中就會出現(xiàn)一條數(shù)據(jù)。