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