python操作mysql数据库实现增删改查
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python操作mysql数据库实现增删改查相关的知识,希望对你有一定的参考价值。
参考
http://www.cnpythoner.com/wiki/string.html
http://395469372.blog.51cto.com/1150982/1748120
http://www.jianshu.com/p/1d09d14976d7
http://ju.outofmemory.cn/entry/51481
cat 1.txt
tomcat 192.1.1.121
redis 192.1.1.121
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys #import pymysql #pymysql.install_as_MySQLdb() import MySQLdb as mdb con = mdb.connect(‘192.1.1.197‘, ‘root‘, ‘xxxxxx‘, ‘db03‘) def db_execute(sql): cursor = con.cursor() ‘‘‘cursor.execute(sql) con.commit() cursor.close()‘‘‘ try: cursor.execute(sql) con.commit() cursor.close() except: con.rollback() def insert_template(file_path): with open(file_path, ‘r‘) as file: for lines in file.readlines(): line = lines.strip(‘\n‘).split() print tuple(line) # sql = ‘insert table(field) values({0});‘.format(line) sql = "INSERT INTO a(apply,ip) VALUES(‘%s‘,‘%s‘)" %tuple(line) print sql db_execute(sql) #print sql_lines def select_template(): cursor = con.cursor() sql = ‘select bb.ip from b bb,a aa where bb.apply = aa.apply group by bb.ip‘ cursor.execute(sql) template_list = cursor.fetchall() res = template_list print res for m in res: print type(m[0]) #template_list = cursor.fetchall() #print template_list def test1(): cursor = con.cursor() id_list = [1, 2, 3] id_list = ‘,‘.join([str(cursor.connection.literal(i)) for i in id_list]) print id_list sql = ‘SELECT col1, col2 FROM table1 WHERE id IN (%s)‘ % id_list print sql def select_template2(): cursor = con.cursor() id_list = [1, 2] sql = ‘SELECT * FROM a WHERE id IN %s‘, (id_list,) print sql #cursor.execute(sql) cursor.execute(‘SELECT ip,apply FROM a WHERE id IN %s‘% (tuple(id_list),)) template_list = cursor.fetchall() res = template_list print res if __name__ == ‘__main__‘: file_path = ‘1.txt‘ insert_template(file_path) #select_template() select_template2()
只写了插入和查询,其他类似。
本文出自 “要有梦想,万一实现了呢” 博客,请务必保留此出处http://szgb17.blog.51cto.com/340201/1971959
以上是关于python操作mysql数据库实现增删改查的主要内容,如果未能解决你的问题,请参考以下文章
48.Python中ORM模型实现mysql数据库基本的增删改查操作