小试python-MySQLdb 安装和使用

来源:互联网 发布:直播弹幕语音助手 mac 编辑:程序博客网 时间:2024/06/07 08:23


MySQLdb 是python用来连接和操作数据库的模块,在使用之前先要进行安装:

1.确保mysql已经安装

可参考:http://www.jb51.net/article/39188.htm

安装页面:http://dev.mysql.com/downloads/file/?id=463242   点击‘Mysql on Windows',安装最新社区版本

安装之后还需要配置(需要实践)

选择Custom 安装方式,选择安装MySQL server, sample and document,



2.安装MySQLdb:

https://pypi.python.org/pypi/MySQL-python/1.2.5 目前最新版本是1.2.5,直接安装第一个.exe就好,安装完成之后,可以试试:

import MySQLdb
如果不报错就是安装成功,另外也可以在交互模式下用:
>>> help()Welcome to Python 2.7!  This is the online help utility.If this is your first time using Python, you should definitely check outthe tutorial on the Internet at http://docs.python.org/2.7/tutorial/.Enter the name of any module, keyword, or topic to get help on writingPython programs and using Python modules.  To quit this help utility andreturn to the interpreter, just type "quit".To get a list of available modules, keywords, or topics, type "modules","keywords", or "topics".  Each module also comes with a one-line summaryof what it does; to list the modules whose summaries contain a given wordsuch as "spam", type "modules spam".help> MySQLdbHelp on package MySQLdb:NAME    MySQLdb - MySQLdb - A DB API v2.0 compatible interface to MySQL.FILE    d:\python27\lib\site-packages\mysqldb\__init__.pyDESCRIPTION    This package is a wrapper around _mysql, which mostly implements the    MySQL C API.        connect() -- connects to server        See the C API specification and the MySQL documentation for more info    on other items.
.....
这样就表明安装成功

3. 官网的使用手册:http://mysql-python.sourceforge.net/MySQLdb.html

4. 来段代码练习下:
import MySQLdbconn=MySQLdb.connect(host='localhost',user='root',passwd='admin',port=3306)cur = conn.cursor()cur.execute("create database sharontest")cur.execute("use sharontest")cur.execute("create table users (id int(2) primary key auto_increment, username varchar(20), age int(2), email varchar(20))")cur.execute("show tables")
可以在mySql交互模式下看看, 记得一定要带冒号: show tables;



以上是通过python-MySQLdb实现了数据库和表的建立
完成之后记得关闭游标和连接:

cur.close()conn.close()



0 0