MySQL数据库以及其Python用法
生活随笔
收集整理的這篇文章主要介紹了
MySQL数据库以及其Python用法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一 命令行模式下:
mysql -u root -p # 進入進入mysql命令行模式 show databases; # 查看所有數據庫 create database data; # 創建數據庫,名為data use blog; # blog 是一個數據庫名 show tables; create table persons(personid int,name varchar(255)); # 在數據庫下創建表persons.show columns from post; # post是數據庫blog中一張表名。 select * from post; select (distinct) title,content from post; # 加distinct后可以去重 select timestamp from post where title='文章標題'; # where為條件語句 SELECT * FROM Websites WHERE alexa > 15 AND (country='CN' OR country='USA'); # and,or對條件過濾 select title from post order by timestamp (desc); # order by 以timestamp排序,默認升序,如要降序加上desc insert into post(title,content,timestamp) values ('title','content','20171207'); # 往post表中插入值 update post set content='google.com' where title='title'; # 更新已存在的字段 delete from post (where title='title'); # 刪除表(表中行) truncate table post; # 只刪除表中內容,不刪除表結構。 drop table persons; # 刪除表 drop database data; # 刪除數據庫二 用Python連接MySQL及使用
import pymysql # 連接mysql conn = pymysql.connect(user='root', password='root', database='gaokao', charset='utf8',cursorclass = pymysql.cursors.DictCursor) # mysql數據庫默認查到結果是tuple類型,加入cursorclass 目的是讓結果為list類型。 conn.autocommit(True) cursor = conn.cursor() # 操作mysql query = ('select id, name from my_school') cursor.execute(query) # 查詢 (不論是什么數據類型,占位符都用%s) query = ('select id, name from my_school where id > %s and id < %s') cursor.execute(query, (7, 12)) # 插入 cursor.execute('insert into post(title,content,timestamp) values (%s,%s,%s)', ('title','content','20171207170844')) # 后面填入的數據是格式可以是list[],也可以是tuple() # 更新 cursor.execute('update post set title=%s,content=%s where id=%s', ('圖書館','圖書館真是個學習和看書的好地方','3')) # set后面連續的條件不能用括號括起來,直接逗號隔開即可。 # 刪除 cursor.execute("delete from post where title='title'") # 獲取數據 cursor.fetchone() cursor.fetchall() # 關閉mysql連接 cursor.close() conn.close()?
轉載于:https://www.cnblogs.com/zongfa/p/8029566.html
總結
以上是生活随笔為你收集整理的MySQL数据库以及其Python用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 'vue' 不是内部或外部命令
- 下一篇: 2017-10-9(Volley使用范例