您的位置:首页 > 编程语言 > Python开发

python3.2.5 + mysql-connector-python-1.2.2-py3.2 连接mysql基本用法

2014-07-08 00:58 686 查看
今天又发现另一个python连接mysql的工具,mysql-connector-python,这是一个由python官方推出的一款连接mysql的工具,对高版本Python有较好的支持。基本使用方法与前文所述的pymysql类似。

在实验中发现conn.commit()语句仅针对存储引擎为InnoDB的数据库明显有效。实验内容如下(所有编码均为utf-8):

创建数据库:

create database ere default charset=utf8


创建数据表:

create table test (

id int primary key auto_increment,

name varchar(10) not null

)ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_bin


实验程序:

import mysql.connector;
conn=mysql.connector.connect(host='localhost',user='root',passwd='123',db='ere',charset='utf8');
cur=conn.cursor();

try:# 清空表中原有数据
    cur.execute('delete from test');
    conn.commit();
    print('删除成功');
except Exception as exp:
    print('删除失败:');
    print(exp)
    
try:
    cur.execute("insert into test values(null,'中国')");#添加记录
    conn.commit();
    print('插入成功',cur.lastrowid);
except Exception as exp:
    print('插入失败');
    print(exp);
<pre name="code" class="python">cur.execute('select * from test');#查询表中记录
for each in cur:
    print(each);



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: