-
#!/usr/bin/python2.7
-
# coding=utf-8
-
-
import MySQLdb
-
import sys
-
-
host = '127.0.0.1'
-
user = 'xxx'
-
pwd = 'xxxx' # to be modified.
-
port = '3306'
-
db = 'test'
-
-
-
if __name__ == '__main__':
-
conn = MySQLdb.connect(host=host, user=user, passwd=pwd, db=db, port=3306, charset='utf8');
-
try:
-
conn.ping()
-
except:
-
print 'failed to connect MySQL.'
-
sql = 'select * from stat_app_open where id = 4128'
-
cur = conn.cursor()
-
cur.execute(sql)
-
row = cur.fetchone()
-
for i in row:
-
print i
-
cur.close()
-
conn.close()
-
sys.exit()
-
# -*- coding: utf-8 -*-
-
#mysqldb
-
import time, MySQLdb
-
-
#连接
-
conn=MySQLdb.connect(host="localhost",user="root",passwd="root",db="test",charset="utf8")
-
cursor = conn.cursor()
-
-
#删除表
-
sql = "drop table if exists user"
-
cursor.execute(sql)
-
-
#创建
-
sql = "create table if not exists user(name varchar(128) primary key, created int(10))"
-
cursor.execute(sql)
-
-
#写入
-
sql = "insert into user(name,created) values(%s,%s)"
-
param = ("aaa",int(time.time()))
-
n = cursor.execute(sql,param)
-
print 'insert',n
-
-
#写入多行
-
sql = "insert into user(name,created) values(%s,%s)"
-
param = (("bbb",int(time.time())), ("ccc",33), ("ddd",44) )
-
n = cursor.executemany(sql,param)
-
print 'insertmany',n
-
-
#更新
-
sql = "update user set name=%s where name='aaa'"
-
param = ("zzz")
-
n = cursor.execute(sql,param)
-
print 'update',n
-
-
#查询
-
n = cursor.execute("select * from user")
-
for row in cursor.fetchall():
-
print row
-
for r in row:
-
print r
-
-
#删除
-
sql = "delete from user where name=%s"
-
param =("bbb")
-
n = cursor.execute(sql,param)
-
print 'delete',n
-
-
#查询
-
n = cursor.execute("select * from user")
-
print cursor.fetchall()
-
-
cursor.close()
-
-
#提交
-
conn.commit()
-
#关闭
-
conn.close()
安装步骤
1.python setup.py build
报错error: command 'gcc' failed with exit status 1
sudo apt-get install python-dev
2.python setup.py install
安装测试
>>>import MySQLdb
使用
a.创建连接
conn=MySQLdb.connect(host=host,user=user,passwd=pwd,db=name,port=3306,charset='utf8')
b.生成游标
cur=conn.cursor()
c.操作游标
执行sql语句
n=cur.execute(sql)
查询数据
n=cur.execute(sql)
for row in cur.fetchone()
print row
for row in cur.fetchall()
print row
for i in row
print i
for row in cur.fetchall()
print row[i]
阅读(1047) | 评论(0) | 转发(0) |