python3操作Mysql数据库基础操作

1. 安装PyMySQL

首先需要安装PyMySQL

下载地址:https://github.com/PyMySQL/PyMySQL

在安装PyMySQL之前还需要安装setuptools,下载地址:https://pypi.python.org/pypi/setuptools

2. 实例操作

import pymysql
#数据库连接
#localhost:服务器地址 username:用户名 password:密码 DATADB:数据库
db = pymysql.connect("localhost","username","password","DATEDB")
#使用cursor()方法创建一个游标对象
cursor  = db.cursor()
sql = "SELECT VERSION()"
#使用execute()方法执行SQL查询
cursor.execute(sql)

#使用fetchone()方法获取单条数据
data = cursor.fetchone()
print("Database version : %s "% data)

#关闭数据库连接
db.close()

3. 常用操作之增删查改

#SQL插入语句
sql = "insert into table_test(list1,list2) values('t1','t2')" 

try:

#执行SQL

	cursor.execute(sql)

#一定要记得提交到数据库执行!!!否则无效

	db.commit()

except:

#如果发生异常回滚数据

	db.rollback()

# SQL 删除语句

sql = "delete from table_test where list1='t1'"

try:

   # 执行SQL语句

   cursor.execute(sql)

   # 提交修改

   db.commit()

except:

   # 发生错误时回滚

   db.rollback()
   # 关闭连接
db.close()

sql = "select * from table_test "

try:

	cursor.execute(sql)

#获取所有记录数据

	results = cursor.fetchall()

	for row in results:
	
		t1	= row[0]
		
		t2 = row[1]

	print(t1,t2)
except:

	print("Error:unable to fetch data")


#关闭数据连接

db.close()

其中在获取查询的数据的时候有几个函数要知道

fetchone():该方法获取下一个查询结果集,结果集是一个对象

fetchall():接受全部的返回结果行

rowcount:这是一个只读属性,并返回执行execute()方法后影响的行数

sql = "update table_test set list1 = 'test1' where list1 = 't1'"

try:

   # 执行SQL语句

   cursor.execute(sql)

   # 提交到数据库执行

   db.commit()

except:

   # 发生错误时回滚

   db.rollback()

# 关闭数据库连接

db.close()

你可能感兴趣的:(python3操作Mysql数据库基础操作)