1. 程式人生 > >python操作mysql數據庫實現增刪改查

python操作mysql數據庫實現增刪改查

mysqldb


參考

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數據庫實現增刪改查