Python连接mysql-添加数据
1.Python3操作数据库-添加数据操作
示例代码:
#!/usr/bin/python
import pymysql;
'''
获取mysql连接对象
'''
def open_connect():
try:
# 创建数据库连接
dbconnect = pymysql.connect("localhost","root","","enquiry");
return dbconnect;
except:
print('打开连接异常');
return None;
'''
数据添加操作
'''
def insert_data(dbconnect,sql):
# 使用cursor()方法获取操作游标
cursor = dbconnect.cursor();
try:
# 执行sql语句
cursor.execute(sql);
# 提交到数据库执行
dbconnect.commit();
return 1;
except:
# 如果发生错误则回滚
dbconnect.rollback();
print('请检查sql语法是否正确');
return 0;
'''
关闭数据库连接
'''
def close_connect(dbconnect):
if dbconnect != None:
dbconnect.close();
# 1.打开连接
dbconnect = open_connect();
# 2.执行添加数据操作
# 准备sql语句
sql = '''INSERT INTO demo(name) VALUES ('Mohan')''';
if dbconnect != None:
res = insert_data(dbconnect,sql);
print(res);
close_connect(dbconnect);
示例截图:
运行截图: