首頁  >  文章  >  後端開發  >  使用python操作mysql資料庫詳解

使用python操作mysql資料庫詳解

高洛峰
高洛峰原創
2017-03-22 10:36:402705瀏覽

基礎環境:Python 3.5.1

mysql版本:5.6.35 (rpm安裝方式)

作業系統:Centos7.3 與windows7

一、python連接資料庫模組介紹:

    目前主要使用的有以下幾種、MySQLdb和pymsql以及mysql官方提供的mysql-connector-python驅動,MySQLdb模組是python2.X使用比較多的,而python3.X使用的pymsql會多一點,以後再研究官方的mysql-connector-python,這次學習以及實作全部都基於pymsql模組。

    PyMySQL的使用方法和MySQLdb幾乎一樣,習慣用MySQLdb的,只要 import MySQLdb 修改為 import pymysql  就可以了。

二、pymysql連接mysql 使用pymysql.connect()方法,可以調整很多參數:

 使用python操作mysql数据库详解#連線範例:

connect=pymysql.connect(host="192.168.186.157",port=3306,user="winner",passwd="123123",db="DB",charset ="utf8",connect_timeout=3000)

範例連線主要包含host,user,passwrd以及port等參數

連線範例2:

connect=pymysql.connect( "192.168.186.157","winner","123123","test")

不用加host等參數,但是格式固定,分別是主機、用戶、 密碼以及初始連接的資料庫不能互換位置,

而上面的帶參數的範例相對來說更隨意一些。

注意:這裡的連接埠以及連線逾時時間都是int,所以不需要帶引號

連線物件回傳的connect()函數:

 使用python操作mysql数据库详解 在python操作mysql資料庫的過程中,我們主要是使用取得遊標方法counect.cursor()和cursor.execute()方法對資料庫進行操作,像建立資料庫以及資料表等操作,我們通常直接在mysql客戶端連接,執行SQL語句就可以了,所以我們更多的操作就是增、刪、改、查等操作

遊標物件也提供了幾種方法:

使用python操作mysql資料庫詳解範例一、連接192.168.186.157的mysql服務端建立pymysql函式庫字元集為utf8

#/usr/bin/env python

##_*_coding :utf-8_*_

#導入pymysql模組

import pymysql

#使用pymysql.connect()方法建立資料庫連結

con=pymysql .connect(host='192.168.186.157',user='winner',passwd='123123',port=3306)

##使用con.cursor()方法建立遊標

#cursor =con.cursor()

sql="  create  database  If Not Exists   pymysql default character set utf8;"

'''sql="""create table if not exists class (id int (10) primary key auto_increment,

 name varchar(20) not null ,address varchar(20) not null default "gansu")""

#'''

#cursor.execute(sql)

cursor.execute("show databases")

dataname=cursor.fetchall()

print(dataname)

執行結果:

(('information_schema',), ('#mysql50#2017-03-16_09-38-47',), ('DB',), ('mysql',), ('performance_schema',),

 ('pymysql',), ('test',), ('winner_mas',))

 Process finished with exit code 0 

範例二、連接剛建立的pymysql資料庫建立class表

/usr/bin/env python

##_*_coding:utf-8_*_

#匯入pymysql模組

import pymysql

##使用pymysql.connect()方法建立資料庫連結

con=pymysql.connect(host='192.168.186.157',user='winner',passwd='123123',port=3306,db= 'pymysql')

使用con.cursor()方法建立遊標

cursor=con.cursor()

##sql="  建立資料庫 如果不存在  pymysql default字元集utf8;"

sql="""如果不存在則建表class (id int(10) 主鍵auto_increment,

 name varchar(20) not null ,address varchar(20 ) not null default "gansu")"""

cursor.execute(sql)

cursor.execute("顯示表格")

dataname=cursor.fetchall( )

print(dataname)

C:\Users\Administrator\AppData\Local\Programs\Python\Python35\python.exe C:/Users/Administrator/PycharmProjects/python/createdatabase. py

(('class',),)

C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-packages\pymysql\cursors.py :166:警告:(1050,「表'類別'已存在」)

結果= self._query(查詢)

進程已完成,退出程式碼0

# # /usr/bin/env python

_*_coding:utf-8_*_

##匯入pymysql模組

import pymysql

#打開資料庫連結

connect=pymysql.connect(host="192.168.186.157",port=3306,user="winner",passwd="123123",db="pymysql",charset="utf8", connect_timeout =3000)

使用cursor方法取得操作遊標

cursor=connect.cursor()

sql=''' insert into class (name,address)

 values("JSP","go"),("winner","back"),("GOOD","contine"),("cursor","execute");

'''

##使用資料庫操作方法

cursor.execute(sql)

#交易提交

#connect.commit()

##data=cursor.execute("select * from class order by id desc" )

##使用fetchall方法取得操作結果

##data=cursor.fetchmany(5)

print(data)

注意:這裡將交易提交的部分註解掉了,特示範一下未提交交易的情況。 )時):

C:\Users\Administrator\AppData\Local\Programs\Python\Python35\python.exe C:/Users/Administrator/PycharmProjects/python/insertmysql.py

( (12, '遊標', '執行'), (11, '好', '繼續'), (10, '獲勝者', '後退'), (9, 'JSP', '繼續'))

進程以退出程式碼0結束

由此我們發現資料庫的事務關係在軟體開發的過程中是相當重要的一部分,所以在對事務處理的時候需要謹慎。

#提交交易的來源程式碼:

/usr/bin/env python

_*_coding:utf-8_*_

#匯入pymysql模組

import pymysql

開啟資料庫連結

connect=pymysql.connect(host="192.168.186.157",port=3306,user="winner",passwd="123123 ",db="pymysql",charset="utf8",connect_timeout=3000)

##使用cursor方法取得操作遊標

cursor=connect.cursor()

# sql=''' 插入類別(名稱,位址)

values("JSP","go"),("winner","back"),("GOOD","contine"), ("遊標","執行");

'''

#使用execute方法操作資料庫

cursor.execute(sql)

#交易提交

connect.commit()

data=cursor.execute("select * from class order by id desc" )

#使用fetchall方法取得操作結果

##data=cursor.fetchall()

print(data)

#!/usr/bin/python

#encoding=utf-8

# -*- coding:utf-8 -*- 

import os

import calendar

#import datetime

import MySQLdb

import os, sys, re,string

import time, tarfile,getopt

import socket

import struct

reload(sys)

sys.setdefaultencoding('utf- 8')

optmap = {

##    'dbuser': 'tongji',

    'dbpass': '64CE0CEE9A85F22C',

#  : '64CE0CEE9A85F22C',

#  :'dbhost': '192.168.1.10',

    'dbport': 3306,

    'dbname': 'web_basic'

}

##code='201613'

now = int(time.time())

msgid=code+str(now)

print msgid

##f = file('/home /haoren/nian/1550035_ACCOUNT_'+msgid+'_0001_V2.xml','w+')

f1 = file('/home/haoren/nian/1550035_RELATIONACCNTININFO_'+ms>gIN+ )

def log(line):

    line = line + "\r\n"

    f.write(line)

    return

def log1(line):

    line = line + "\r\n"

    f1.write(line)

#    return

def sql_select(reqsql):

    try:

        db_conn = MySQLdb.connect(user=optmap['dbuser'], passwd=optmap['dbpass'], hostdbpass'], hostdbpass'][' dbhost'], port=optmap['dbport'], db=optmap['dbname'], charset='utf8')

        db_cursor=db_conn.cursor()

##    db  ("use %s"%optmap['dbname'])

        count = db_cursor.execute(reqsor)

        ret ()

        db_conn.close

#        db_conn.close

#       e.args[0], e.args[1])

    return ''

def getusercoin():

    reqsql = "select * from singer_auth where status =##    reqsql = "select * from singer_auth where status = 10 and ip !='NULL' AND (signtype = '1' OR signtype = '3') limit 150 ;"

    #print reqsql

    ret = sql_select(reqsql))

#    n = 0

    for row in ret:

        n += 1

        if n <  100 :

#        if n <  100 :

#        if n < 1])+','+str(row[8])

##卷                print str(row[0])

             

                print str(row[2])

                print str(row[3])

# ' 和 str (row[10]).strip() == '0':

                        print str(row[9]) +',')+ str[10]))  print str(row[9]) +','o+ str[10]))) 名詞##  (row[9]).strip() == '0' and str(row[10]).strip() != '0':

                        print str(row[9]) +' '+str(row[10]).split('/')[6]

                elif str(row[9]).strip() != '0' 與str(row[10]) .strip() == '0':

                        print str(row[9]).split('/')[6] +','+str(row[10])

                else:

                        print str(row[9]).split('/')[plit('/')[6]

        else:

                n = 0

getusercoin()

f.close()

##getusercoin()

f.close()

##.

##!/usr/bin/env python

#-*-coding:utf-8-*-

#明細

import MySQLdb

導入os, sys, re,string

導入時間, tarfile,getopt

optmap = {

                'dbuser' : 'haoren',

                'dbpass' : 'FqDxhG4d',

                'dbhost, : '192.168.1.10,   ' : 3306,

               '資料庫名稱': 'JSDB '

                 }

def get_files(dir,pattern):

        res_file_list =[]

#        res_file_list =[]

##                cur_file_list = os.listdir(dir)

                    if re.search(pattern, file_name):

                               res_file_list.append(file_name )

                return res_file_list

        else:

       # cur_day = time.strftime( "%Y%m%d", time.localtime(time.time()-86400))

        opts, args = getopt.getopt(sys.argv[1:], 'd:')

        對於op,opts 中的值:

                if op == '-d':

                        m = re.search('[0-9]{8}' , value)

                          if m:

           c

                        else:

                   生活中編號                                return 'no'

#        log_day = time.strftime('#1%) m%d', time.localtime(time.mktime(time.strptime(cur_day, '%Y%m%d'))))

        fmt_day = time.strftime('%Y-%m- %d', time.localtime(time.mktime(time.strptime(cur_day, '%Y%m%d'))))

        print '結算統計日期:',fmt_day

#        #log_day = time.strftime("%y%m%d", time.localtime(time.time()-86400))

#        dirname="/home/haoren/logd

        dirname="/home/haoren/logdir/%s_67%"% log_day

        print dirname

        db_conn = MySQLdb.connect(user=optmap['dbuser'], passwd=hostoptmap['dbpass'], host=optmap'dbuser'], passwd= optmap['dbport'], db=optmap['dbname'])

        db_cursor=db_conn.cursor()

        db_conn.)

        db_conn..)

        db_conn..)

        db_conn.query("使用%s"%optmap ])

        tabletime = time.strftime("%y%m%d", time.localtime(time.mktime(time.strptime(cur_day, "%Y%m%d"))))

        sql="CREATE TABLE IF NOT EXISTS `JIESUANTONGJI_%s` like JIESUANTONGJISAMPLE"%tabletime

  SU    IE ONGJI_% 中刪除s"%tabletime)

        if os.path.exists("/tmp/JieSuanTongJi2016.txt"):

           "):

           )

        file_list2=get_files(dirname,'billserver')

        for file2 in file_list2:

  1  grep -h -w 結算統計 |grep -v 人民幣消費結算統計 >> /tmp/JieSuanTongJi2016.txt"%(dirname,file2)

                os.system(command)

##   #  放在結算tmp/JieSuanTongJi2016.txt'

        record = {}

        a_file = open(filename, 'r')

#1:  INFO: [結算統計]時間(1453690814)類別(1)名稱(購物卡收入)平台(3977962)等級(2)使用者(65147500)購物卡(1)個購物卡(39)給客戶(65147500),客戶等級(28),承包商(1),員工人民幣(100),客戶獲得人民幣(8000),平台獲得人民幣(2000),當前客戶人民幣(1320960)平台當前人民幣(335560)

## 

#     平台當前人民幣(335560)#####      平台當前人民幣( a_line in a_file.readlines():######                        m = re.search("^(時間\S+) Bill\[\d+\])\INFO: \[結算類別\ ((\d+)\)名稱\((\S+)\)平台\((\d+)\)等級\((\d+)\)使用者\((\d+)\)語音\((\ d+) \)個購物卡\((\d+)\)給客戶\((\d+)\)、客戶等級\((\d+)\)、簽約\((\d+)\)、耗費人民幣\ (( \d+)\),客戶取得人民幣\((\d+)\),平台取得人民幣\((\d+)\),客戶當前人民幣\((\d+)\)平台目前人民幣\((\ d+) \)", a_line)######                        if m:######        問            #print "第二項:" +m.group(2)###

                    #print "第三項:"+m.group(3)

                   #print "第五項目:"+m.group(5)

                    #print "第兩個項目:"+m.group(6)

      +  7)

                    #print "第八項:"+m.group(8)

              group 

             所示:  #print "第十項:"+m.group(10)

                    #print "第十一項:"+m.group(11)

  :"+m.group(12)

                    #print "第十三項:"+m.group(13)

       group (14)

                    #print "第十五項:"+m.group(15)

              

                    #print "第十七項:"+m.group(17)

              #                      if int( m.group(14)) >0 or int(m.group(15)) >0 :

                         db_conn.query("insert into JIESUANTONGJI_%s(OPTIME,TYPE,ITEMNAME,CHANNELID,CHANNELLEVEL ,PRESENTERID,ITEMNUM,ITEMID,SINGERID,SINGERLEVEL,SIGN,CONSUMECOIN,SINGERRECVGOLD,CHANNELRECVGOLD,CURRENTSINGERGOLD,CURRENTCHANNELGOLD) values(%d,%d,'%s',%d%,ANNELGOLD) 值,%d,%d,%d,%d,%d,%d,%d,%d)"%(tabletime,int(m.group(2)),int(m.group(3)), str(m.group(4)),int(m.group(5)),int(m.group(6)),int(m.group(7)),int(m.group(8)), int(m.group(9)),int(m.group(10)),int(m.group(11)),int(m.group(12)),int(m.group(13)), int(m.group(14)),int(m.group(15)),int(m.group(16)),int(m.group(17))))

        a_file.close ()

        db_conn.commit()

        db_cursor.close()

        db_conn.close()

        db_conn.close()

main( #if __name__ == "__main__":

#        main()

以上是使用python操作mysql資料庫詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn