python数据库操作 - PyMySQL入门
Oct 17, 2016 am 11:21 AMPyMySQL是Python中操作MySQL的模块,和之前使用的MySQLdb模块基本功能一致,PyMySQL的性能和MySQLdb几乎相当,如果对性能要求
不是特别的强,使用PyMySQL将更加方便,PyMySQL是完全使用python编写,避免了MySQLdb跨系统分别安装的麻烦。
适用环境
python版本 >=2.6或3.3
mysql版本>=4.1
安装
在命令行下执行命令:
pip install pymysql
手动安装,请先下载。下载地址:https://github.com/PyMySQL/PyMySQL/tarball/pymysql-X.X。
其中的X.X是版本。
下载后解压压缩包。在命令行中进入解压后的目录,执行如下的指令:
python setup.py install
建议使用pip安装, 可以自动解决包依赖问题,避免安装中出现各种错误。
pymysql的基本操作如下:
#!/usr/bin/env python # --coding = utf-8 # Author Allen Lee import pymysql #创建链接对象 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='Allen') #创建游标 cursor = conn.cursor() #执行sql,更新单条数据,并返回受影响行数 effect_row = cursor.execute("update hosts set host = '1.1.1.2'") #插入多条,并返回受影响的函数 effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)",[("1.0.0.1",1,),("10.0.0.3",2)]) #获取最新自增ID new_id = cursor.lastrowid #查询数据 cursor.execute("select * from hosts") #获取一行 row_1 = cursor.fetchone() #获取多(3)行 row_2 = cursor.fetchmany(3) #获取所有 row_3 = cursor.fetchall() #重设游标类型为字典类型 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) #提交,保存新建或修改的数据 conn.commit() #关闭游标 cursor.close() #关闭连接 conn.close()

Article chaud

Outils chauds Tags

Article chaud

Tags d'article chaud

Bloc-notes++7.3.1
Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise
Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1
Puissant environnement de développement intégré PHP

Dreamweaver CS6
Outils de développement Web visuel

SublimeText3 version Mac
Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Sujets chauds

Comment utiliser la belle soupe pour analyser HTML?

Comment télécharger des fichiers dans Python

Comment utiliser Python pour trouver la distribution ZIPF d'un fichier texte

Comment travailler avec des documents PDF à l'aide de Python

Comment se cacher en utilisant Redis dans les applications Django

Comment effectuer l'apprentissage en profondeur avec TensorFlow ou Pytorch?

Comment implémenter votre propre structure de données dans Python
