1、安装MySQL数据库
参考文档:Windows上安装配置mysql
2、安装MySQL的Python驱动
1)mysql.connector
mysql-connector 是 MySQL 官方提供的驱动器, 它在Python中重新实现MySQL协议,它比较慢,但不需要C库,因此可移植性好。
pip install mysql-connector
2)pymysql
pymysql是由yutaka.matsubara开发维护的纯python实现的mysql模块。它相对于mysql.connector, MYSQLdb来说比较年轻。它的效率和可移植性和my-connector理论上是差不多的。
pip install pymysql
3)MYSQLdb(MysqlClient)
MySQLdb是一个围绕_mysql简化的Python包装器,它使_mysql与Python DB API接口兼容(v2.0)。其中_mysql也是该作者开发的模块,它依赖C库,则MYSQLdb也是依赖C库的,可移植性不太好。MysqlClient 是 Python 操作 MySql 的一个驱动程序,是 MySQL-python 的另外一个分支,目前MySQL-python 只支持到Python2,而 MysqlClient 支持 Python3 并且修复了一些bug。
MYSQLdb:
pip install MySQL-python
MysqlClient:
pip install mysqlclient
3、连接数据库
1)mysql.connector
import mysql.connector conn = mysql.connector.connect(host='localhost', user='root', passwd='yourpasswd', db='db', charset='utf8')
2)MYSQLdb(MysqlClient)
MYSQLdb:
import MySQLdb conn = MySQLdb.connect(host='localhost', user='root', passwd='yourpasswd', db='db', charset='utf8')
MysqlClient:
import mysql.connector mydb = mysql.connector.connect( host="localhost", # 数据库主机地址 user="yourusername", # 数据库用户名 passwd="yourpassword" # 数据库密码 )
3)pymysql
import pymysql conn = pymysql.connect(host='localhost', user='root', passwd='yourpasswd', db='db', charset='utf8' cursorclass=pymysql.cursors.DictCursor)
4、创建数据库和数据表
1)创建数据库
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456" ) mycursor = mydb.cursor() mycursor.execute("CREATE DATABASE cjavapy")
2)创建数据表
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456", database="cjavapy" ) mycursor = mydb.cursor() mycursor.execute("CREATE TABLE sites (name VARCHAR(1024), url VARCHAR(512))")
3)输出所有数据库
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="123456" ) mycursor = mydb.cursor() mycursor.execute("SHOW DATABASES") for x in mycursor: print(x)
5、增删改查
1)增加, 删除,修改
import mysql.connector #import MySQLdb #import pymysql #import mysql.connector #选择一种驱动即可,连接注意一下,其它基本相同 conn = mysql.connector.connect(host="localhost", user="root", passwd="123456") cursor = conn.cursor() sql1 = "insert into tablename values (%s, %s, %s)" cursor.execute(sql1,(1,2,3)) cursor.executemany(sql1,[(1,2,3),(4,5,6)]) conn.commit() sql2 = "delete from tablename where cursor.execute(sql2) conn.commit() sql3 = "update tablename set columnname = %s where cursor.execute(sql3, (0,1230)) cursor.executemany(sql, [(0,1030),(2,1230)]) conn.commit() cursor.close() conn.close()
2)查询
import mysql.connector #import MySQLdb #import pymysql #import mysql.connector #选择一种驱动即可,连接注意一下,其它基本相同 conn = mysql.connector.connect(host="localhost", user="root", passwd="123456") cursor = conn.cursor() sql1 = "select * from main limit 10" cursor.execute(sql) result1 = cursor.fetchall() # 取出所有数据 result2 = cursor.fetchone() # 取出第一条数据 result3 = cursor.fetchmany(5) # 取出结果中的五条数据 cursor.close() conn.close()