Python访问MySQL数据库

# -*- coding: utf-8 -*-
# Author: areful
#
# needs module 'mysql-connector-python', running command below to install it:
# pip install mysql-connector-python
#
#
# remote connect mysql(on Ubuntu18.04.1 64bit, MySQL5.7, ip=192.168.147.130, MySQL port 3306):
# modify /etc/mysql/mysql.conf.d/mysqld.cnf:
# from "bind-address = 127.0.0.1" to "#bind-address = 127.0.0.1"
#
# mysql> use mysql;
# mysql> update user set authentication_string=password('新密码') where user='root';
# mysql> flush privileges;
# mysql> quit
#
# GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '123456' WITH GRANT OPTION;
#
import mysql.connector

conn = mysql.connector.connect(host='192.168.147.130', port='3306', database='test',
                               user='root', password='123456', use_unicode=True)
cursor = conn.cursor()
# 创建user表:
cursor.execute('CREATE TABLE IF NOT EXISTS user (id VARCHAR(20) PRIMARY KEY, name VARCHAR(20))')
# 插入一行记录,注意MySQL的占位符是%s:
cursor.execute('INSERT INTO user (id, name) VALUES (%s, %s)', ['1', 'Michael'])
var = cursor.rowcount
# 提交事务:
conn.commit()
cursor.close()
# 运行查询:
cursor = conn.cursor()
cursor.execute('SELECT * FROM user WHERE id = %s' % ('1',))
values = cursor.fetchall()
print(values)

# 关闭Cursor和Connection:
cursor.close()
conn.close()

  

猜你喜欢

转载自www.cnblogs.com/SevenCD/p/10369569.html