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

python & MySQLdb(one)

时间:2018-11-03 16:29:41      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:com   har   god   select   count   except   res   过程   host   

python开发过程中用到数据库无外乎MYSQL,Mangodb,redis三种,三者数据库使用可能存在差异,但在一些基础的语句使用时都是大同小异的,这阶段学习了一些基础操作,记录下

add:

# -*- coding: utf-8 -*-
import MySQLdb
try:
  conn=MySQLdb.connect(host=192.168.65.146,port=3306,db=student,user=root,passwd=toor,charset=utf8)
  csl=conn.cursor()
  count=csl.execute("insert into stu(stu_id,stu_name,stu_phone,stu_hometown) values(‘0003‘,‘kj‘,‘19564832601‘,河北)")
  print(count)
  conn.commit()
  csl.close()
  conn.close()
except Exception as e:
  print (e).

delete:

# -*- coding:utf-8 -*-
import MySQLdb
try:
    conn=MySQLdb.connect(host=192.168.65.146,port=3306,db=student,user=root,passwd=toor,charset=utf8)
    cs1=conn.cursor()
    count=cs1.execute("delete from stu where stu_id=4")
    print(count)
    conn.commit()
    conn.close()
except Exception as e:
    print(e)

update:

# -*- coding:utf-8 -*-
import MySQLdb
try:
    conn=MySQLdb.connect(host=192.168.65.146,port=3306,db=student,user=root,passwd=toor,charset=utf8)
    cs1=conn.cursor()
    count=cs1.execute("update stu set stu_phone=‘10005954565‘ where stu_name=‘张良‘")
    print(count)
    conn.commit()
    conn.close()
except Exception as e:
    print(e)

search:

# -*- coding: utf-8 -*-
import MySQLdb
try:
    conn=MySQLdb.connect(host=192.168.65.146,port=3306,db=student,user=root,passwd=toor,charset=utf8)
    cs1=conn.cursor()
    #cs1.execute("select * from stu where stu_id=1")
    #result=cs1.fetchone()  查询一行
    cs1.execute("select * from stu")
    result=cs1.fetchall()#查询全部
    print(result)
    cs1.close()
    conn.close()
except Exception as e:
    print(e)

python & MySQLdb(one)

标签:com   har   god   select   count   except   res   过程   host   

原文地址:https://www.cnblogs.com/kk328/p/9901026.html

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