####零、开发环境
操作系统:Ubuntu 16.04 及以上 或 Windows 8 及以上
Python版本:3.5及以上
开发工具:PyCharm
数据库:MySQL
####一、环境配置
- 创建虚拟环境
- 通过命令行进入虚拟环境,输入命令在虚拟环境中安装MySQL Client:
pip install mysqlclient
####二、简单讲解
在这篇文章中我会利用 mysqlclinet 这个库,对数据库进行简单的操作。操作数据库之前,需要先连接到数据库(默认数据库已创建),只需要调用 MySQLdb.connect 传递数据库地址、端口号、用户名、密码和要操作的数据库名称,这样就创建了对数据的链接,代码如下:
conn=MySQLdb.connect( host='192.168.0.102',#数据库地址 port=3306,#端口号 user='root',#数据库用户名 passwd='123*asd',#密码 db='news',#操作的数据库 charset='utf8' #数据库编码规则 )
获取到数据库链接就可以对数据库进行***增删改查***的操作了,进行数据库操作首先要获取游标,通过 conn.cursor() 获得,代码如下:
cursor = conn.cursor()
在获得到游标后,就可调用 execute 来操作数据库。这里需要注意,对数据库进行增、删、改的时候余姚在调用 execute 方法后,再调用commit方法,将内存中的数据写入数据库。完整代码见三
####三、示例代码
import MySQLdb class MysqlSearch(object): def __init__(self): self.get_conn() def get_conn(self): try: self.con = MySQLdb.connect( host='192.168.0.102', port=3306, user='root', passwd='123*asd', db='news', charset='utf8' ) except MySQLdb.Error as e: print('Error %d:%s' % (e.args[0], e.args[1])) def close_conn(self): try: if self.con: self.con.close() except MySQLdb.Error as e: print('Error: %s' % e) def get_one(self): # 准备SQL sql = 'select * from news where news_type = %s order by created_at desc; ' # 找到cursor cursor = self.con.cursor() # 执行SQL cursor.execute(sql, ('百家',)) # 拿到结果 rest = dict(zip([k[0] for k in cursor.description], cursor.fetchone())) # 处理数据 print(rest['title']) # 关闭cursor/链接 cursor.close() self.close_conn() def add_one(self): try: # 准备SQL sql = "INSERT INTO news (title,img_url,content,news_type) VALUE " \ "(%s,%s,%s,%s);" # 获取链接和cursor cursor = self.con.cursor() # 提交数据到数据库 cursor.execute(sql, ('标题1', '/static/img/news/01.png', '新闻内容1', '推荐',)) # 提交事务 self.con.commit() except: self.con.rollback() # 关闭cursor和连接 cursor.close() self.close_conn() def main(): obj = MysqlSearch() obj.add_one() if __name__ == '__main__': main()