python 操作MySQL

in #blog6 years ago

build in python3.5.2

create a database and create a table in python

import pymysql

connect the database

the argvs based on the database you set.

Generally speaking, you should change the No. of the port 3306 , because it's easy to be attack

localhost = 127.0.0.1

conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='231495877')
curs = conn.cursor()

create a database named hashaki

Ensure the program can run multiple times,we should use try...exception

try:
curs.execute('create database hashaki')
except:
print('Database hashaki exists!')
conn.select_db('hashaki')

create a table named hashakifields

try:
curs.execute('create table hashakifields(id int PRIMARY KEY NOT NULL,name text)')
except:
print('The table hashakifields exists!')

sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""

try:

执行sql语句

curs.execute(sql)

提交到数据库执行

conn.commit()
except:

如果发生错误则回滚

conn.rollback()

conn.commit()
curs.close()
conn.close()