码迷,mamicode.com
首页 > 数据库 > 详细

Python3 MySQL

时间:2017-10-09 22:53:57      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:std   bsp   root   imp   col   fetch   back   key   exist   

首先安装pymysql  pip install pymysql

技术分享

准备数据库:创建一个数据库testdb

mysql实例:

import pymysql

#打开数据库连接,使用数据库所在的IP127.0.0.1,数据库的用户名和密码,要操作的数据库testdb
db=pymysql.connect(127.0.0.1,root,‘‘,testdb)

#使用cursor()创建一个游标对象
cursor=db.cursor()

#使用 execute() 方法执行 SQL,如果表存在则删除
cursor.execute(drop table if exists user;)

#创建表的SQL语句
sql=‘‘‘create table user (
            id int(10) primary key,
            user varchar(20)
            );
        ‘‘‘

#执行sql语句
cursor.execute(sql)

#插入数据的SQL语句
sql1="insert into user values(1,tangqiu);"

try:
  #执行SQL语句
    cursor.execute(sql1)
    db.commit()
except :
  #发生错误时回滚
    db.rollback()
#查询的SQL语句 sql2=select * from user; #执行SQL语句 cursor.execute(sql2) # 获取所有记录列表 result=cursor.fetchall() print(result) db.close()

 

Python3 MySQL

标签:std   bsp   root   imp   col   fetch   back   key   exist   

原文地址:http://www.cnblogs.com/tangqiu/p/7642994.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!