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

python mysql

时间:2016-07-02 14:33:51      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

mysql

Linux

  • 安装mysql: apt-get install mysql-server
  • 安装python-mysql模块:apt-get install python-mysqldb

Windows

  • 下载安装mysql
  • python操作mysql模块:MySQL-python-1.2.3.win32-py2.7.exe 或 MySQL-python-1.2.3.win-amd64-py2.7.exe
  • mysql图形界面:Navicat_for_MySQL

安装完成后,导入MySQLdb测试是否安装成功

数据库:

技术分享
show databases;
use [databasename];
create database  [name];

数据表:

技术分享
技术分享
show tables;

create table students
    (
        id int  not null auto_increment primary key,
        name char(8) not null,
        sex char(4) not null,
        age tinyint unsigned not null,
        tel char(13) null default "-"
    );
技术分享

增删改查:

技术分享
技术分享
insert into students(name,sex,age,tel) values(alex‘,man‘,18,151515151)

delete from students where id =2;

update students set name = sb‘ where id =1;

select * from students
技术分享

MySQLdb

技术分享
技术分享
#!/usr/bin/env python
#coding:utf-8

import MySQLdb

‘‘‘
conn = MySQLdb.connect(host=‘127.0.0.1‘,user=‘root‘,passwd=‘1234‘,db=‘07day05db‘)

cur = conn.cursor()

reCount = cur.execute(‘insert into UserInfo(Name,Address) values(%s,%s)‘,(‘alex‘,‘usa‘))

conn.commit()

cur.close()
conn.close()

print reCount
‘‘‘

‘‘‘
conn = MySQLdb.connect(host=‘127.0.0.1‘,user=‘root‘,passwd=‘1234‘,db=‘07day05db‘)

cur = conn.cursor()

reCount = cur.execute(‘delete from UserInfo‘)

conn.commit()

cur.close()

conn.close()

print reCount
‘‘‘

‘‘‘
conn = MySQLdb.connect(host=‘127.0.0.1‘,user=‘root‘,passwd=‘1234‘,db=‘07day05db‘)
cur = conn.cursor()

li =[
     (‘alex‘,‘usa‘),
     (‘sb‘,‘usa‘),
]
reCount = cur.executemany(‘insert into UserInfo(Name,Address) values(%s,%s)‘,li)

conn.commit()
cur.close()
conn.close()

print reCount
‘‘‘

‘‘‘
conn = MySQLdb.connect(host=‘127.0.0.1‘,user=‘root‘,passwd=‘1234‘,db=‘07day05db‘)
cur = conn.cursor()

reCount = cur.execute(‘update UserInfo set Name = %s‘,(‘alin‘,))

conn.commit()
cur.close()
conn.close()

print reCount
‘‘‘

‘‘‘
#fetchone/fetchmany(num)   
conn = MySQLdb.connect(host=‘127.0.0.1‘,user=‘root‘,passwd=‘1234‘,db=‘07day05db‘)
cur = conn.cursor()

reCount = cur.execute(‘select * from UserInfo‘)

print cur.fetchone()
print cur.fetchone()
cur.scroll(-1,mode=‘relative‘)
print cur.fetchone()
print cur.fetchone()
cur.scroll(0,mode=‘absolute‘)
print cur.fetchone()
print cur.fetchone()

cur.close()
conn.close()

print reCount
‘‘‘

#fetchall

conn = MySQLdb.connect(host=127.0.0.1‘,user=root‘,passwd=1234‘,db=07day05db)
#cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
cur = conn.cursor()

reCount = cur.execute(select Name,Address from UserInfo)

nRet = cur.fetchall()


cur.close()
conn.close()

print reCount
print nRet
for i in nRet:
    print i[0],i[1]
技术分享

注意:cur.lastrowid

真实开发中的mysqlhelper怎么写?

python mysql

标签:

原文地址:http://www.cnblogs.com/cp-miao/p/5635236.html

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