import pymysql
def getMysqlConn():
conn = pymysql.connect(host="172.16.238.130", port=3306, db="my_mysql", user="root", password="123456", charset="utf8")
return conn
def userSql(conn, sql):
cs = conn.cursor()
cs.execute(sql)
conn.commit()
cs.close()
conn.close()
def main():
# 创建数据的连接,编写sql语句,增加数据
# conn = getMysqlConn()
# insertSql = '''insert into goods (name, cname, bname, price) values ("http", "docket", "apache", 30.00)'''
# userSql(conn, insertSql)
# # 创建数据库连接,编写sql语句,删除数据
# conn = getMysqlConn()
# deleteSql = '''delete from goods where id=11'''
# userSql(conn, deleteSql)
# # 创建数据库连接,编写sql语句,修改数据
# conn = getMysqlConn()
# updateSql = '''update goods set name="www" where id=12'''
# userSql(conn, updateSql)
# 单条查询
# 创建数据库连接
conn = getMysqlConn()
# 创建游标
myCursor = conn.cursor()
# 编写查询sql语句
inquireSql = '''select * from goods where id=13'''
# 执行sql语句
ret = myCursor.execute(inquireSql)
# 打印查询到的条数
print(ret)
# 从游标中拿出数据
inquireData = myCursor.fetchall()
# 打印单条数据
print(inquireData)
# 多条查询
# 创建数据库连接
conn = getMysqlConn()
# 创建游标
myCursor = conn.cursor()
# 编写查询sql语句
inquireSql = '''select * from goods'''
# 执行sql语句
ret = myCursor.execute(inquireSql)
# 打印查询到的条数
print(ret)
# 获取数据
oneData = myCursor.fetchone()
allData = myCursor.fetchall()
# 打印获取的数据
print(oneData)
print(allData)
# 关闭游标及数据库的连接
myCursor.close()
conn.close()
if __name__ == "__main__":
main()