通过python操作mysql数据库
2017-03-11 19:46
369 查看
1. ubuntu下安装mysql-server
在ubuntu16.04下通过命令sudo apt install mysql-server安装mysql服务器。然后为了让python练级数据库然后通过pip工具安装mysql-connector。即在命令行界面输入:pip install mysql-connector。
2. 连接数据库
def test_connect(): config = { "host": "127.0.0.1", "user": "root", "password": "******", "port": 3306, "database": "test", "charset": "utf8", } try: cnn = mysql.connector.connect(**config) print("success connected!") return cnn except mysql.connector.Error as e: print('connected failed {}!'.format(e))
3. 创建表
def create_table(_cnn): ''' :param _cnn:连接器 :return: 建表语句中的名称均可以用``来括起来,注意此处不是单引号 ''' sql = 'CREATE TABLE students2' \ '(id INT(10) NOT NULL AUTO_INCREMENT,' \ 'name VARCHAR(20) DEFAULT NULL,' \ 'PRIMARY KEY(id))' \ 'DEFAULT CHARSET=utf8' cursor = _cnn.cursor() try: cursor.execute(sql) except mysql.connector.Error as e: print('created failed {}!'.format(e))
4. 插入数据
def insert_data(_cnn): cursor = _cnn.cursor() try: # 直接字符串插入方式 sql_insert1 = 'insert into students(id, name) VALUES(2, "xie")' cursor.execute(sql_insert1) # 元组插入方式,此处%s是占位符不是格式化字符串所以id也对应%s sql_insert2 = "insert into students(id, name) VALUES(%s, %s)" datas = (11, "hello") cursor.execute(sql_insert2, datas) # 字典插入方式 sql_insert3 = "insert into students(id, name) VALUES(%(id)s, %(name)s)" data_dic = {'id': 12, 'name': 'hi'} cursor.execute(sql_insert3, data_dic) #多次插入 stmt = "insert into students(id, name) VALUES (%s, %s)" datas = [(5, 'many'), (6, 'happy'), (7, 'just a test')] cursor.executemany(stmt, datas) print('insert completed!') except mysql.connector.Error as e: print('inserted failed {}!'.format(e)) finally: cursor.close() # 此处的数据库引擎是Innodb,执行完后需要执行commit进行事务提交 _cnn.commit() _cnn.close()
5. 查询操作
def query_data(_cnn): cursor = _cnn.cursor() try: sql = 'select name from students where id=%s' cursor.execute(sql, (2,)) for name in cursor: print(name) except mysql.connector.Error as e: print('query failed {}!'.format(e)) finally: cursor.close() _cnn.close()
6. 删除操作
def delete_data(_cnn): cursor = _cnn.cursor() try: sql = 'delete from students where id=%s' cursor.execute(sql, (2,)) print('delete complete!') except mysql.connector.Error as e: print('deleted failed {}!'.format(e)) finally: cursor.close() _cnn.commit() _cnn.close()
相关文章推荐
- 树莓派安装mysql数据库并且通过python来进行存储操作
- python3通过pymysql连接MySQL数据库操作
- 用python操作mysql数据库(之通过类实现,方便添加功能)
- Python通过pymsql操作Mysql数据库环境搭建
- python通过elixir包操作mysql数据库实例代码
- python 通过mysqldb 操作mysql数据库
- Python实战之MySQL数据库操作
- MySQL数据库通过JDBC操作,简单查询
- 通过pythong MySQLdb操作mysql数据库的例子
- python操作mysql数据库注意
- python操作MySQL数据库
- Python实战之MySQL数据库操作
- 转]在Linux下编译安装MySQL并通过C语言操作MySQL数据库
- python操作MySQL数据库
- python学习笔记--操作mysql数据库
- Python2.7操作Mysql数据库及乱码解决方案(附mysqldb win32 py2.7下载)
- python操作MySQL数据库的方法分享
- Python连接以及操作MySQL数据库详解
- Python Mysql数据库操作 Perl操作Mysql数据库
- 黄聪:python+MySQLdb操作Mysql数据库示例代码程序教程