python配置MySQL数据库(windows系统)

python配置MySQL数据库(windows系统)


1、MySQL配置

前提是windows上已经安装了MySQL数据库,且配置完毕,能正常建表能操作。在此基础上只需安装MySQL-python-1.2.4b4.win32-py2.7.exe就ok了,只有1M多。


链接:https://wiki.python.org/moin/DatabaseInterfaces

MySQL for python:https://wiki.python.org/moin/MySQL


安装只需要双击exe程序默认安装就行了。


2、调用

MySQLdb 是用于Python链接Mysql数据库的接口,它实现了 Python 数据库 API 规范 V2.0,基于 MySQL C API 上建立的。

(1)引入模块

命令:import  MySQLdb


(2)连接数据库

使用conn=MySQLdb.connect('localhost','root','','company',3306)连接报错:



使用db = MySQLdb.connect("127.0.0.1","root","","company",3306)或者db = MySQLdb.connect('127.0.0.1','root','','company',3306)连接成功。

表示host=127.0.0.1,user=root,passwd='' ";db="company",port=3306


(3)新建数据库

>>> db = MySQLdb.connect('127.0.0.1','root','','company',3306)	#连接数据库
>>> db.query('Create database test')				#创建一个数据库test
>>> 

(4)关闭数据库

命令:db.close()


(5)查看数据库

>>> import MySQLdb as mdb
>>> connection=mdb.connect('127.0.0.1','root','','company',3306)
>>> cursor = connection.cursor(mdb.cursors.DictCursor)
>>> cursor.execute("show databases")
6L
>>> print (cursor.execute("show databases"))
6
>>> result = cursor.fetchall()
>>> print result
({'Database': 'information_schema'}, {'Database': 'company'}, {'Database': 'mysql'}, {'Database': 'performance_schema'},
			 {'Database': 'students'}, {'Database': 'test'})
>>> cursor.close()
>>> connection.close()


(6)查看数据库中的表格

>>> import MySQLdb as mdb
>>> connection=mdb.connect('127.0.0.1','root','','company',3306)
>>> cursor = connection.cursor(mdb.cursors.DictCursor)
>>> cursor.execute("show tables")
10L
>>> result = cursor.fetchall()
>>> print result
({'Tables_in_company': 'dd_base'}, {'Tables_in_company': 'ddbase'}, {'Tables_in_company': 'p_base'}, {'Tables_in_company': 'pt_base'},
 {'Tables_in_company': 't_dept'}, {'Tables_in_company': 't_employee'}, {'Tables_in_company': 't_loader'}, {'Tables_in_company': 'tt_base'},
 {'Tables_in_company': 'tt_dept'}, {'Tables_in_company': 'ty_base'})
>>> cursor.close()
>>> connection.close()


  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值