python连接mysql

python连接mysql的例子。

mysql不使用默认端口号时,修改db_port为mysql的端口。

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
45
46
47
48
49
50
51
52
53
54
import pymysql


db_port = 3306
db_charset = 'utf8'
db_name = 'testdb'
db_host = '127.0.0.1'
db_user_name = 'flame'
db_user_pwd = 'flame999'


cx = pymysql.connect(host=db_host, user=db_user_name, password=db_user_pwd, database=db_name, charset=db_charset, port=db_port)


# execute sql
def execute_sql(sql, args=None):
cu = cx.cursor()
try:
ret = cu.execute(sql, args)
cx.commit()
except Exception as e:
print(sql)
raise e
return False, 0
finally:
cu.close()
return False, 0
return True, ret


# execute sql
def execute_fetchall(sql, args=None):
cu = cx.cursor()
record_set = []
if cu.execute(sql, args):
record_set = cu.fetchall()
cu.close()
return record_set


# execute sql
def execute_fetchone(sql, args=None):
cu = cx.cursor()
record_set = []
if cu.execute(sql, args):
record_set = cu.fetchone()
cu.close()
return record_set

execute_sql("select * from table")
execute_fetchall("select * from table")
execute_fetchone("select * from table")

cx.close()