本例以Windows, Python 3.4 为基础,来演示使用Python在My SQL数据库中创建表。

相关

关于使用Python创建My SQL连接:
Python(3.x) My SQL 数据库连接

创建表

mysql_create_table.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import mysql.connector

def createTable(config):
conn = mysql.connector.Connect(**config)
#print(conn)
cur = conn.cursor()

tbl = "STUDENT"
#drop the table first if exist
stmt_drop = "DROP TABLE IF EXISTS {0}".format(tbl)
print("Drop Table SQL : ", stmt_drop)
cur.execute(stmt_drop)

#create new table
stmt_create = (
"CREATE TABLE {0} ("
" ID TINYINT UNSIGNED NOT NULL AUTO_INCREMENT, "
" NAME VARCHAR(50) DEFAULT '' NOT NULL, "
" AGE TINYINT DEFAULT NULL, "
" BRD date DEFAULT NULL, "
" CREATEDT datetime DEFAULT NULL, "
" PRIMARY KEY (ID))"
).format(tbl)

print("Create SQL :" , stmt_create)

cur.execute(stmt_create)

cur.close()
conn.close()

if __name__ == '__main__':
config = {
'host': 'localhost',
'port': 3306,
'database': 'test',
'user': 'root',
'password': '!qaz2wsx',
'charset': 'utf8',
'use_unicode': True,
'get_warnings': True,
}

createTable(config)

运行结果:

1
2
Drop Table SQL :  DROP TABLE IF EXISTS STUDENT
Create SQL : CREATE TABLE STUDENT ( ID TINYINT UNSIGNED NOT NULL AUTO_INCREMENT, NAME VARCHAR(50) DEFAULT '' NOT NULL, AGE TINYINT DEFAULT NULL, BRD date DEFAULT NULL, CREATEDT datetime DEFAULT NULL, PRIMARY KEY (ID))