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()

Coin Marketplace

STEEM 0.27
TRX 0.13
JST 0.031
BTC 61745.50
ETH 2898.66
USDT 1.00
SBD 3.61