python3连接数据库mysql

Python  连接数据库需要安装正确的 数据库驱动 ,比如 MySQLdb、psycopg2。如果需要尝试连接 池(database pool)功能,还得装下DBUtils。

PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb,并且mysqldb不再支持python3.x。
2.安装pymysql:pip3 install PyMySQL

Python连接mysql

import pymysql

# 打开数据库连接(host,端口,账户,密码,数据库,字符)

db = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='user', charset='utf8')

# 使用cursor()方法获取操作游标

cursor = db.cursor()

# 使用预处理语句

sql = """CREATE TABLE EMPLOYEE (

         FIRST_NAME  CHAR(20) NOT NULL,

         LAST_NAME  CHAR(20),

         AGE INT, 

         SEX CHAR(1),

         INCOME FLOAT )"""

try:

   # 执行sql语句

   cursor.execute(sql)

   # 提交到数据库执行

   db.commit()

except:

   # 如果发生错误则回滚

   db.rollback()

cursor.execute("SELECT VERSION()")  #执行sql查询

print(dir(cursor))

datas=cursor.fetchone()  #获取单条数据

print(datas)

# 关闭游标

cursor.close()

# 关闭数据库连接

db.close()

猜你喜欢

转载自www.cnblogs.com/volcano-li/p/13173783.html