Python操作Mysql數據庫

一、下載導入第三方庫:

        1.pip install pymysql

        2.直接在pycharm中導入

二、閱讀源碼,得知連接需要的參數,以及類型:

 

得知最少需要,主機名、用戶名、密碼、數據庫以及端口號,且端口號爲整形,其餘爲str

三、Demo:

tips:注意一下事物的提交,以及sql注入問題,有點格式化輸出的意思

from pymysql import *
try:
    con = connect('localhost', 'root', 'usbw', 'skh', 3306)
except MySQLError as msg:
    print(msg)
cur = con.cursor()
#查詢
count = cur.execute("select * from qwe")
print(count)
result = cur.fetchall()
for i in result:
    print(i)
#增加
count1 = cur.execute("insert into qwe values(%d, %s, %s, %s, %d)" %(101, "'Python'", "'Mysql'", "'Sex'", 1))
con.commit()
print(count1)
#刪除
count2 = cur.execute("delete from qwe where id = %d" %(4))
con.commit()
print(count2)
count2 = cur.execute("update qwe set password = %s where id = %d" %("'PyMysql'", 101))
con.commit()
print(count2)
cur.close()
con.close()


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章