1、快速開始前端
對於會用MySQL的朋友來講,開始使用pymysql能夠說真的so esay,只要用下面的代碼,把想要對數據庫的操做放在 sql = " " 裏就能夠了。mysql
沒有接觸過MySQL的小夥伴能夠先學一下SQL。sql
上一篇文章是關於mysql入門的,能夠參考一下。(只是本身入門的學習筆記,歡迎交流指正)數據庫
import pymysql # 鏈接數據庫 conn = pymysql.connect( host=「數據庫地址(localhost)」, user=「用戶名」, password=「密碼」, database=「數據庫名」, charset=「utf8」) # 獲得一個能夠執行SQL語句的光標對象且結果集默認以元組顯示 cursor = conn.cursor() # 獲得一個能夠執行SQL語句而且將結果做爲字典返回的遊標 #cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 定義要執行的SQL語句 sql = """ create table fav_table ( id INT auto_increment primary key, user VARCHAR(128), ess INT )CHARACTER SET utf8; """ cursor.execute(sql) #對數據庫進行寫操做要提交(建表不算) #conn.commit() cursor.close() conn.close()
2、批量操做django
import pymysql conn = pymysql.connect( host='主機IP(或localhost)', port=端口號, user='root', password='123456', database='數據庫名', charset='utf8' ) cursor = conn.cursor() #sql ='insert into userinfo (user,ess) values (%s,%s);' #user = 'user_1' #ess = 1 #cursor.execute(sql, [name, ess]) sql = 'insert into userinfo(user,ess) values(%s,%s);' data = [ ('user_1', 110), ('user_2', 120), ('user_3', 479) ] # 拼接並執行sql語句 cursor.executemany(sql, data) conn.commit() cursor.close() conn.close()
3、結合Django,從前端獲取數據,返回HtppResponseapp
#views.py import pymysql from django.http import HttpResponse def add_fav(request): conn = pymysql.connect( host='localhost', user='root', password='buzhidao', database='wapp_shuer', charset='utf8' ) user = request.POST.get('re_user') ess = request.POST.get('re_ess') data = [user,ess] cursor = conn.cursor() sql = "insert into fav_table (user, ess) value (%s, %s);" res = cursor.execute(sql,data) conn.commit() cursor.close() conn.close() return HttpResponse(res)
PS:這是最原生的經過pymysql包對mysql數據庫的操做方法。下一篇關於Django的文章裏,咱們會用Django的models操做數據庫。學習