python3操作MySQL資料庫

來源:互聯網
上載者:User

標籤:

安裝PyMySQL

:https://pypi.python.org/pypi/PyMySQL

 

1.把操作Mysql資料庫封裝成類,資料庫和表先建好

import pymysql.cursors# ======== Setting linked test databases ===========host = ‘192.168.17.123‘user = ‘root‘password = ‘123456‘db=‘polls‘# ======== MySql base operating ===================class MySQLOperating():    def __init__(self):        try:            # Connect to the database            self.connection = pymysql.connect(host = host,                                              user = user,                                              password = password,                                              db = db,                                              charset = ‘utf8mb4‘,                                              cursorclass = pymysql.cursors.DictCursor)        except pymysql.err.OperationalError as e:            print("Mysql Error %d: %s" %(e.args[0], e.args[1]))    # clear table data    def clear(self, table_name):        real_sql = "delete from " + table_name + ";"        with self.connection.cursor() as cursor:            cursor.execute("SET FOREIGN_KEY_CHECKS = 0;")            cursor.execute(real_sql)        self.connection.commit()
def insert(self, table_name, data): for key in data: data[key] = "‘" + str(data[key]) + "‘" key = ‘,‘.join(data.keys()) value = ‘,‘.join(data.values()) real_sql = "INSERT INTO " + table_name + " (" + key + ") VALUES (" + value +")" with self.connection.cursor() as cursor: cursor.execute(real_sql) self.connection.commit() # close database def close(self): self.connection.close()if __name__ == ‘__main__‘: db = MySQLOperating() table_name = "poll_question" data = {‘id‘:1, ‘question_text‘:‘you buy pro6?‘} db.clear(table_name) db.insert(table_name, data) db.close()

 

2.插入資料

import sysimport MySQLOperating# Inster table datasdef insert_data(table, datas):    db = MySQLOperating()    db.clear(table)    for data in datas:        db.insert(table, data)    db.close()#Create datatable_poll_question = "polls_question"datas_poll_question =[ {‘id‘: 1, ‘question_text‘: ‘you buy pro6?‘, ‘pub_date‘:‘2016-07-23 09:58:56.000000‘}]table_poll_choice = "polls_choice"datas_poll_choice =[{‘id‘: 1, ‘choice_text‘: ‘buy‘, ‘votes‘: 0, ‘question_id‘: 1},                              {‘id‘: 2, ‘choice_text‘: ‘not buy‘, ‘votes‘: 0, ‘question_id‘: 1},]# init datadef init_data():    insert_data(table_poll_question, datas_poll_question)    insert_data(table_poll_choice, datas_poll_choice)if __name__ == ‘__main__‘:    init_data()

 

3.更新資料

 

python3操作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.