Python中操作MySQL入门实例

yipeiwu_com6年前Python基础

一、安装MySQL-python

复制代码 代码如下:

# yum install -y MySQL-python

二、打开数据库连接
复制代码 代码如下:

#!/usr/bin/python
import MySQLdb

conn = MySQLdb.connect(user='root',passwd='admin',host='127.0.0.1')
conn.select_db('test')
cur = conn.cursor()


三、操作数据库
复制代码 代码如下:

def insertdb():
    sql = 'insert into test(name,`sort`) values ("%s","%s")'
    exsql = sql % ('hello','python')
    cur.execute(exsql)
    conn.commit()
    return 'insert success'

def selectdb():
    sql = 'select `name` from test where `sort` = "%s"'
    exsql = sql % ('python')
    count = cur.execute(exsql)
    for row in cur:
        print row

    print 'cursor move to top:'
    cur.scroll(0,'absolute')

    row = cur.fetchone()
    while row is not None:
        print row
        row = cur.fetchone()

    print 'cursor move to top:'
    cur.scroll(0,'absolute')

    many = cur.fetchmany(count)
    print many

def deletedb():
    sql = 'delete from test where `sort` = "%s"'
    exsql = sql % ('python')
    cur.execute(exsql)
    conn.commit()
    return 'delete success'


print insertdb()
print insertdb()
selectdb()
print deletedb()

四、关闭连接

复制代码 代码如下:

cur.close()
conn.close()

注意顺序。

相关文章

pyqt5对用qt designer设计的窗体实现弹出子窗口的示例

1. 用qt designer编写主窗体,窗体类型是MainWindow,空白窗口上一个按钮。并转换成mainWindow.py # -*- coding: utf-8 -*- #...

Python 函数基础知识汇总

一、函数基础 简单地说,一个函数就是一组Python语句的组合,它们可以在程序中运行一次或多次运行。Python中的函数在其他语言中也叫做过程或子例程,那么这些被包装起来的语句通过一个函...

Python 使用requests模块发送GET和POST请求的实现代码

①GET # -*- coding:utf-8 -*- import requests def get(url, datas=None): response = reques...

Python文件操作中进行字符串替换的方法(保存到新文件/当前文件)

题目: 1.首先将文件:/etc/selinux/config 进行备份 文件名为 /etc/selinux/config.bak 2.再文件:/etc/selinux/config 中...

python中aioysql(异步操作MySQL)的方法

python异步IO初探 探索异步IO执之前,先说说IO的种类 1.阻塞IO最简单,即读写数据时,需要等待操作完成,才能继续执行。进阶的做法就是用多线程来处理需要IO的部分,缺点是开销会...