Home > Database > Mysql Tutorial > MySQLdb库连接MySQL数据库_MySQL

MySQLdb库连接MySQL数据库_MySQL

WBOY
Release: 2016-06-01 13:13:03
Original
906 people have browsed it

Python DB-API是Python的数据库应用程序接口,支持包括Oracle,MySQL,DB2,MSSQL,Sybase等主流数据库,但不同的数据库,需要下载不同的模块,比如说:MySQLdb模块支持MySQL. 虽然模不一样,但所有这些API执行步骤是一致的:

1. 导入API模
2. 获取与数据库的连接.
3. 发出SQL语句和存储过程.
4. 关闭连接

下面以MySQLdb模块来做说明:

安装

首先必须安装。

Windows下载链接:http://www.codegood.com/archives/4

插入

import MySQLdb#建立和mysql数据库的连接dbconn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='abcd')#获取游标cursor1 = conn.cursor()#执行SQL,创建一个数据库cursor1.execute("drop database if exists test")cursor1.execute("create database test")#选择连接哪个数据库dbconn.select_db('test')try:	#执行SQL,创建一个表	cursor1.execute("create table log(id int,message varchar(50))")	#插入一条记录	value = [0,"Log Information ID is:0"]	curs.execute("insert into log values(%s,%s)",value)	#插入多条记录	values = []	for i in range(1,11):		values.append((i,'Log Information ID is:' + str(i)))	curs.executemany("insert into log values(%s,%s)",values)	#提交修改							 	conn.commit()except:
Copy after login
# 如果有任何错误,则回滚	conn.rollback()#关闭游标连接,释放资源curs.close()#关闭连接conn.close()
Copy after login
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template