標籤:資料 .com l資料庫 關閉 int style print 擷取 date
python操作mysql資料庫 python3中操作mysql資料需要安裝一個第三方模組,pymysql,使用pip install pymysql安裝即可,在python2中是MySQLdb模組,在python3中沒有MySQLdb模組了,所以使用pymysql。
一、操作資料
操作資料庫分為以下幾個步驟
1.連上資料庫 帳號 密碼 ip 連接埠號碼 資料庫
2.建立遊標
3.執行sql
4.擷取結果
5.關閉遊標
6.連結關閉
1 sql_connect = pymysql.connect( 2 host=‘118.24.3.40‘,user=‘jxz‘,passwd=‘123456‘, 3 port=3306,db=‘jxz‘,charset=‘utf8‘ 4 #port必須寫int類型 5 #charset這裡必須寫utf8 6 ) 7 cur = sql_connect.cursor()#建立遊標 8 cur.execute(‘select * from stu;‘)#執行sql 9 res = cur.fetchall()#擷取所有返回結果10 11 # cur.execute(‘insert into stu VALUE (6,"ytt","女");‘)12 # delete update insert 語句都需要commit一下13 # sql_connect.commit()14 15 print(res)16 cur.close()#關閉遊標17 sql_connect.close()#關閉連結
將操作資料庫寫一個函數
1 def my_db(host,user,passwd,db,sql,port=3306,charset=‘utf8‘): 2 import pymysql 3 coon = pymysql.connect(user=user, 4 host=host, 5 port=port, 6 passwd=passwd, 7 db=db, 8 charset=charset 9 )10 cur = coon.cursor()#建立遊標11 cur.execute(sql)#執行sql12 if sql.strip()[:6].upper()==‘SELECT‘:13 res = cur.fetchall()14 print(res)15 else:16 coon.commit()17 res = ‘ok‘18 cur.close()19 coon.close()20 return res
python--操作資料庫