首页 > 代码库 > (13)python连接msql
(13)python连接msql
python连接mysql两种方法
一、python官网提供的 MySQL-python 软件
下载地址
https://pypi.python.org/pypi/MySQL-python/1.2.5 (MySQL-python-1.2.5.win32-py2.7.exe )
http://download.csdn.net/detail/seven_zhao/6607625(MySQL-python-1.2.3.win-amd64-py2.7)
安装时如果报一下错误
Python version 2.7 required, which was not found in the registry
用一下方法解决
方法:转自(http://www.cnblogs.com/min0208/archive/2012/05/24/2515584.html)
新建一个register.py 文件,把一下代码贴进去,保存(G盘)
# # script to register Python 2.0 or later for use with win32all # and other extensions that require Python registry settings # # written by Joakim Loew for Secret Labs AB / PythonWare # # source: # http://www.pythonware.com/products/works/articles/regpy20.htm # # modified by Valentine Gogichashvili as described in http://www.mail-archive.com/distutils-sig@python.org/msg10512.html import sys from _winreg import * # tweak as necessary version = sys.version[:3] installpath = sys.prefix regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version) installkey = "InstallPath" pythonkey = "PythonPath" pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % ( installpath, installpath, installpath ) def RegisterPy(): try: reg = OpenKey(HKEY_CURRENT_USER, regpath) except EnvironmentError as e: try: reg = CreateKey(HKEY_CURRENT_USER, regpath) SetValue(reg, installkey, REG_SZ, installpath) SetValue(reg, pythonkey, REG_SZ, pythonpath) CloseKey(reg) except: print "*** Unable to register!" return print "--- Python", version, "is now registered!" return if (QueryValue(reg, installkey) == installpath and QueryValue(reg, pythonkey) == pythonpath): CloseKey(reg) print "=== Python", version, "is already registered!" return CloseKey(reg) print "*** Unable to register!" print "*** You probably have another Python installation!" if __name__ == "__main__": RegisterPy()
安装成功后,
1、导入模块
import MySQLdb
如果没报错说明安装成功
2、创建连接对象,传入参数
conn=MySQLdb.connect(host=‘localhost‘,user=‘root‘,passwd=‘abc‘,db=‘db_meng‘,port=3306)
3、创建游标对象并获取数据库连接
cur=conn.cursor()
4、执行sql
增删改和建库建表的纯sql语句
cur.execute()
例如:
cur.execute(‘CREATE TABLE tb_meng7(id INT,name1 VARCHAR(50)‘)
5、关闭游标
cur.close()
6、提交事物
conn.commit()
7、关闭数据库连接
conn.close()
8、显示查询数据
每次只显示一行,游标向后移动一位
cur.fetchone()
9、查询结果,游标控制
定位到查询的第一条数据
cur.scroll(0,‘absolute‘)
10、获得多条数据,必须要指定数据条数
info = cur.fetchmany(i)
然后用遍历的方法,得出所有数据
for ii in info: print ii
完整代码:
二、mysql connector python v2.1.6 for python v2.7
mysql 5.7.18.1 里附带的软件(别的版本没用过,只能拿这个举例子)
mysql下载地址 https://dev.mysql.com/downloads/mysql/
安装时选自定义可以看到此选项
安装成功后
import mysql.connector
如果没报错说明安装成功
(13)python连接msql
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。