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)