python的mysql小代碼

來源:互聯網
上載者:User

標籤:NPU   %s   技術   star   串連   one   sql   readlines   idt   

我因為懶,就想寫個批量insert資料的小代碼 這裡是代碼

 

# _*_ encoding:utf-8 _*_import osimport MySQLdbimport numpy as npdbname = ‘spj‘db = MySQLdb.connect(host="localhost", port=3306, user="root", passwd="1234", db=dbname,charset="utf8")  # 進行插入操作時需要聲明編碼類別型cursor = db.cursor()def dp_insert(file_name,putin):    file = open(file_name, "r")    for line in file.readlines():#插入        arr = line.split()        sql = putin+‘ values ‘+‘(‘+"‘"+arr[0]+"‘"+‘,‘+"‘"+arr[1]+"‘"+‘,‘+"‘"+arr[2]+"‘"+‘,‘+"‘"+arr[3]+"‘"‘)‘+‘;‘        try:            cursor.execute(sql)            db.commit()        except:            print("Error")    file.close()def select(putin):    sql = putin    try:        cursor.execute(sql)        results = cursor.fetchall()        for row in results:            print(row)        db.commit()    except:        print("Error: unable to fecth data")def describe(putin):    sql = putin    try:        cursor.execute(sql)        results = cursor.fetchall()        for row in results:            print(row)        db.commit()    except:        print("Error: unable to fecth data")def delete_line(infile,outfile):    infopen = open(infile,‘r‘)    outfopen = open(outfile,‘w‘)    lines = infopen.readlines()    for line in lines:        if line.split():            outfopen.writelines(line)        else:            outfopen.writelines("")    infopen.close()    outfopen.close()    os.remove(infile)    os.rename(outfile,infile)def main():    file_name = ‘p.txt‘    print("please input sql:")    putin = input()    delete_line(file_name, ‘new.txt‘)  # test pass    if putin.startswith(‘insert‘):  # +‘,‘+"‘"+arr[2]+"‘"        print("資料的path")        file_name = input()        dp_insert(file_name, putin)    elif putin.startswith(‘select‘):        select(putin)    elif putin.startswith(‘describe‘):        describe(putin)    else:        db.close()        os._exit()if __name__ == ‘__main__‘:    main()    print("next?")    if input()==‘Y‘:        main()    else:        db.close()        os._exit()    db.close()    #insert 模板    #insert into p(pno, sname, color, weight)

 

(insert語句:insert into j(jno,jname,city))

 

這裡是一些檔案處理的代碼,之前放在代碼裡,看著難受,放在這裡

# 讀取path目錄下的檔案名稱,返迴文件名list列表 def readFileName(path): lists = [] for root, dirs, files in os.walk(path): for file in files: lists.append(os.path.join(root, file)) return lists# 刪除路徑為filepath的檔案 def delFile(filepath): os.remove(filepath) print "ok"‘‘‘‘‘‘#轉化為數組for line in open("p.txt","r"): arr =line.split() print(arr)#轉化為列表file = open("p.txt", "r")list_arr = file.readlines()for i in range(len(list_arr)): list_arr[i] = list_arr[i].strip()a = np.array(list_arr)print(a)file.close()‘‘‘#sql=‘‘+‘‘+‘‘+‘‘ 加號串連 sql=‘%s%s%s’ % (‘‘,‘‘,‘‘)

python的mysql小代碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.