小试python-MySQLdb 安装和使用



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 out
the 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 writing
Python programs and using Python modules.  To quit this help utility and
return 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 summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".

help> MySQLdb
Help on package MySQLdb:

NAME
    MySQLdb - MySQLdb - A DB API v2.0 compatible interface to MySQL.

FILE
    d:\python27\lib\site-packages\mysqldb\__init__.py

DESCRIPTION
    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 MySQLdb

conn=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()



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值