學習如何在python中使用MySQL

來源:互聯網
上載者:User

標籤:for   value   tps   idt   logs   htm   create   upd   date   

一開始遇到了許多問題 在pycharm中import mysql、MySQLdb都沒有用,最後查了些資料,發現在python3.x中 已經改為了pip install MySQLClient

然後import MySQLdb就可以了

之後串連上資料庫 可以做一些 簡單的增刪改操作

注意:增刪改代碼最好加try。。exception。。finally 進行檢查

 

import MySQLdb
conn=MySQLdb.connect(host=‘127.0.0.1‘,port=3306,user=‘root‘,passwd=‘fanxiaoqian‘,db=‘test‘,charset=‘utf8‘)

cursor=conn.cursor()

cursor.execute(‘‘‘
create table if not EXISTS user
(
userid bigint(11) PRIMARY KEY ,
username VARCHAR(20)
)

‘‘‘)
for i in range(10):
cursor.execute("insert into user(userid,username) values(‘%d‘,‘%s‘)" %(int(i),‘name‘+str(i)))

conn.commit()
# res=cursor.fetchall()
# for row in res:
# print(row)
#
# sql=‘select * from user‘
# cursor.execute(sql)
# print(cursor.rowcount)
#
# rs = cursor.fetchone()
# print(rs)
#
# rs = cursor.fetchmany(3)
# print(rs)
# rs=cursor.fetchall()
# print(rs)

sql_insert = ‘insert into user(userid,username) values(10,"name10")‘
sql_update = ‘update user set username="name91" where userid=9‘
sql_delete = ‘delete from user where userid=3‘

cursor.execute(sql_insert)
print(cursor.rowcount)
cursor.execute(sql_update)
print(cursor.rowcount)
cursor.execute(sql_delete)
print(cursor.rowcount)


conn.commit()

 

參考部落格 :https://www.cnblogs.com/itdyb/p/5700614.html

學習如何在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.