日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

python 调用mysql_Python调用Mysql

發布時間:2024/7/23 数据库 47 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python 调用mysql_Python调用Mysql 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

最近在學習Python,發現Python的眾多類庫給Python開發帶來了極大的便利性。

由于項目中使用Mysql,就考慮嘗試使用Python調用Mysql,方便寫一些調試用的小程序代碼。花了半天差了些資料,自己動手,做了個簡單的demo,步驟如下:

1)到Python.org上查找所用的包,我下載的是mysql.connector。

2)代碼編寫,import mysql.connector:

主要分為5個步驟:

(a)連接數據庫: conn = mysql.connector.connect(host='localhost', user='root',passwd='pwd',db='test')

(b)獲取操作句柄:cursor = conn.cursor()

(c)執行sql:cursor.execute(sql)、cursor.executemany(sql, val)

(d)獲取查詢結果:alldata = cursor.fetchall()

(e)關閉連接:cursor.close()、conn.close()

下面是測試用代碼:僅供參考:

import os, sys, string

import mysql.connector

def main():

#connect to mysql

try:

conn = mysql.connector.connect(host='localhost', user='root',passwd='pwd',db='test')

except Exception, e:

print e

sys.exit()

# get cursor

cursor = conn.cursor()

# create table

sql = 'create table if not exists product(Prd_name varchar(128) primary key, Count int(4))'

cursor.execute(sql)

#insert one data

sql="insert into product(Prd_name, Count) values('%s', %d)" % ("ATG", 200)

try:

cursor.execute(sql)

except Exception, e:

print e

#insert some datas

sql ?= "insert into product(Prd_name, Count) values(%s, %s)"

val ?= (("PPS", 400), ("Jr",150), ("Smt", 25))

try:

cursor.executemany(sql, val)

except Exception, e:

print e

#quary data

sql = "select * from product"

cursor.execute(sql)

alldata = cursor.fetchall()

#print data

if alldata:

for rec in alldata:

print rec[0],rec[1]

cursor.close()

conn.close()

if __name__ == "__main__":

main()

print("\nIt's OK")

總結

以上是生活随笔為你收集整理的python 调用mysql_Python调用Mysql的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。