程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python operation MySQL database

編輯:Python

Python operation mysql database

import pymysql
def createUserTable():
conn = pymysql.connect('localhost', user="root", passwd="123456", db="test_zheng")
cursor = conn.cursor()
cursor.execute('drop table if exists user')
sql = """ CREATE TABLE IF NOT EXISTS `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `age` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0"""
cursor.execute(sql)
cursor.close() # Close the cursor first 
conn.close() # Then close the database connection 
print(' Data table created successfully ')
def insertUser():
conn = pymysql.connect('localhost',user = "root",passwd = "123456",db = "test_zheng")
cursor = conn.cursor()
insert = cursor.execute("INSERT into user (`name` ,age) VALUES ('tom',18);")
cursor.close()
conn.commit()
conn.close()
print(' Add the number of rows affected by the statement :', insert)
def insertUser2():
conn = pymysql.connect('localhost',user = "root",passwd = "123456",db = "test_zheng")
cursor = conn.cursor()
sql = "INSERT into user (`name` ,age) VALUES (%s,%s)"
insert = cursor.execute(sql,("Jeff.zheng",18))
cursor.close()
conn.commit()
conn.close()
print(' Add the number of rows affected by the statement :', insert)
def updateUser():
conn = pymysql.connect('localhost',user = "root",passwd = "123456",db = "test_zheng")
cursor = conn.cursor()
sql = "UPDATE `user` set age =21 where name='Jeff.zheng'"
insert = cursor.execute(sql)
cursor.close()
conn.commit()
conn.close()
print(' Add the number of rows affected by the statement :', insert)
def selectUser():
conn = pymysql.connect('localhost',user = "root",passwd = "123456",db = "test_zheng")
cursor = conn.cursor()
sql = "select * from user"
result = cursor.execute(sql)
while 1 :
res=cursor.fetchone()
if res is None:
break
else:
print(res)
cursor.close()
conn.commit()
conn.close()
print(' Add the number of rows affected by the statement :',result)
if __name__ == '__main__':
# createUserTable()
selectUser()

If you can't, it's pip install pymysql Download dependency


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved