pip升级安装pyMysql

mysqldb支持到python3.4,python3.5可以借用pymysql链接mysql数据库。

安装pymysql

    升级pip到最新版本

            python -m pip install --upgrade pip

pip升级安装pyMysql_第1张图片 升级pip

   安装pymysql

           pip install PyMySQL​

pip升级安装pyMysql_第2张图片 安装pymysql

连接mysql

   创建数据库

CREATETABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `email`varchar(255) COLLATE utf8_bin NOT NULL, `password` varchar(255) COLLATEutf8_bin NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULTCHARSET=utf8 COLLATE=utf8_binAUTO_INCREMENT=1 ;

   建立连接

import pymysql.cursors

# Connect to the database

connection = pymysql.connect(host='localhost',

​                                                   user='user',

                                                   password='passwd',

                                                   db='db',

                                                   charset='utf8mb4',

                                                   cursorclass=pymysql.cursors.DictCursor)

try:

   with connection.cursor() as cursor:

       # Create a new record

       sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"

       cursor.execute(sql, ('[email protected]', 'very-secret'))

# connection is not autocommit by default. So you must commit to save

# your changes.

connection.commit()

with connection.cursor() as cursor:

       # Read a single record

       sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"

       cursor.execute(sql, ('[email protected]',))

       result = cursor.fetchone()

       print(result)

finally:

    connection.close()

输出结果:

{'password': 'very-secret', 'id': 1}​​

你可能感兴趣的:(Python)