本例以Windows, Python 3.4 为基础,来演示使用python 插入数据到My SQL数据库。

相关

创建表:
Python(3.x) Create Table 创建表

或者使用SQL创建表:

1
2
3
4
5
6
7
8
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)
)

插入数据

my_sql_insert.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
import mysql.connector
from datetime import datetime
from datetime import date

def insetData(config):
conn = mysql.connector.Connect(**config)
cur= conn.cursor()

tbl = "STUDENT"
#insert data
created = datetime.now()
students = (("Jack", 27, date(1990, 3, 27), created), ("Zhao San", 21, date(1995, 10, 21), created))

stmt_insert = "Insert into {0} (name, age, brd, CREATEDT) values (%s, %s, %s, %s)".format(tbl)
#print(stmt_insert)
try:
cur.executemany(stmt_insert, students)
conn.commit()
except (mysql.connector.errors.Error, TypeError) as exc:
print("Insert has error :", exc)

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,
}

insetData(config)

运行结果: