我因为懒,就想写个批量insert数据的小代码 这里是代码

# _*_ encoding:utf-8 _*_
import os
import MySQLdb
import numpy as np dbname = 'spj'
db = MySQLdb.connect(host="localhost", port=3306, user="root", passwd="", db=dbname,charset="utf8") # 进行插入操作时需要声明编码类型
cursor = db.cursor() def dp_insert(file_name,putin):
file = open(file_name, "r")
for line in file.readlines():#插入
arr = line.split()
sql = putin+' values '+'('+"'"+arr[0]+"'"+','+"'"+arr[1]+"'"+','+"'"+arr[2]+"'"+','+"'"+arr[3]+"'"')'+';'
try:
cursor.execute(sql)
db.commit()
except:
print("Error")
file.close() def select(putin):
sql = putin
try:
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
print(row)
db.commit()
except:
print("Error: unable to fecth data") def describe(putin):
sql = putin
try:
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
print(row)
db.commit()
except:
print("Error: unable to fecth data") def delete_line(infile,outfile):
infopen = open(infile,'r')
outfopen = open(outfile,'w')
lines = infopen.readlines()
for line in lines:
if line.split():
outfopen.writelines(line)
else:
outfopen.writelines("")
infopen.close()
outfopen.close()
os.remove(infile)
os.rename(outfile,infile) def main():
file_name = 'p.txt'
print("please input sql:")
putin = input()
delete_line(file_name, 'new.txt') # test pass
if putin.startswith('insert'): # +','+"'"+arr[2]+"'"
print("数据的path")
file_name = input()
dp_insert(file_name, putin)
elif putin.startswith('select'):
select(putin)
elif putin.startswith('describe'):
describe(putin)
else:
db.close()
os._exit() if __name__ == '__main__':
main()
print("next?")
if input()=='Y':
main()
else:
db.close()
os._exit()
db.close() #insert 模板
#insert into p(pno, sname, color, weight)

(insert语句:insert into j(jno,jname,city))

这里是一些文件处理的代码,之前放在代码里,看着难受,放在这里

# 读取path目录下的文件名,返回文件名list列表
def readFileName(path):
lists = []
for root, dirs, files in os.walk(path):
for file in files:
lists.append(os.path.join(root, file))
return lists # 删除路径为filepath的文件
def delFile(filepath):
os.remove(filepath)
print
"ok"
''' '''
#转化为数组
for line in open("p.txt","r"):
arr =line.split()
print(arr) #转化为列表
file = open("p.txt", "r")
list_arr = file.readlines()
for i in range(len(list_arr)):
list_arr[i] = list_arr[i].strip()
a = np.array(list_arr)
print(a)
file.close()
'''
#sql=''+''+''+'' 加号连接 sql=‘%s%s%s’ % ('','','')

python的mysql小代码的更多相关文章

  1. Python操作Mysql实例代码教程在线版(查询手册)_python

    实例1.取得MYSQL的版本 在windows环境下安装mysql模块用于python开发 MySQL-python Windows下EXE安装文件下载 复制代码 代码如下: # -*- coding ...

  2. Python操作Mysql实例代码教程在线版(查询手册)

    本文介绍了Python操作MYSQL.执行SQL语句.获取结果集.遍历结果集.取得某个字段.获取表字段名.将图片插入数据库.执行事务等各种代码实例和详细介绍,代码居多,是一桌丰盛唯美的代码大餐   实 ...

  3. Python之字符串小代码解析

    本篇只是拿一段代码来对python中的字符串的一些使用做解释,来让大家更加了解python Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:25: ...

  4. Python装饰器小代码

    # coding=utf-8import timedef outer(fun): def inner(): start = time.time() fun() runtime = time.time( ...

  5. 解决Python往MySQL插入中文时报错的问题

    今天遇到一个问题,用Python往MySQL插入数据时,若数据中包含中文会报类似下面的错误: ERROR 1366: Incorrect string value: '\xE4\xB8\xAD\xE5 ...

  6. 利用Python操作MySQL数据库

    前言 在工作中,我们需要经常对数据库进行操作,比如 Oracle.MySQL.SQL Sever 等,今天我们就学习如何利用Python来操作 MySQL 数据库. 本人环境:Python 3.7.0 ...

  7. 使用Python编程语言连接MySQL数据库代码

    使用Python编程语言连接MySQL数据库代码,跟大家分享一下: 前几天我用python操作了mysql的数据库,发现非常的有趣,而且python操作mysql的方法非常的简单和快速,所以我把代码分 ...

  8. Python小代码_2_格式化输出

    Python小代码_2_格式化输出 name = input("name:") age = input("age:") job = input("jo ...

  9. Python小代码_1_九九乘法表

    Python小代码_1_九九乘法表 max_num = 9 row = 1 while row <= max_num: col = 1 while col <= row: print(st ...

随机推荐

  1. Python随笔--继承

  2. 将float数据类型转换为str

    示例程序: #include <stdio.h> . . void UART_send_byte(char dat); void UART_send_string(unsigned cha ...

  3. C++二维数组、指针、对象数组、对象指针

    项目中用到,随手记一下: 1.二维数组.与指针 创建二维数组指针的方式: a.已知一维的大小 1 int **array=new int *[rows]; 2 (for int i=0;i<ro ...

  4. Atom本地安装插件右上角出现红色报错解决方案

    在github上搜索你相中的插件(Package),并下载ZIP包或直接克隆项目到本地.然后将该包直接复制到C盘中的用户下的 .atom\packages\ 文件夹下,注意 atom前面有一个点. 然 ...

  5. 设置ul的指定li 样式

    设置ul的最后li 的样式 .custom-consumerIndex .card-content .list-block ul li:last-child .item-inner { border- ...

  6. Gurobi在Python环境里安装与使用(Windows环境)

  7. python练习:实现一个整数数组里面两个数之和为183的所有整数对

    l1 = [183,0,1,2,-184,367] num = [] for i in range (0,len(l1)): for l in range (i+1,len(l1)): if l1[i ...

  8. MYSQL ini 配置文件详解及性能优化方案

    my.ini分为两块:Client Section和Server Section.   Client Section用来配置MySQL客户端参数.   要查看配置参数可以用下面的命令: show va ...

  9. ABP中mapping中忽略属性

    创建一个XXXXProfile继承Profile,然后在构造函数中写忽略相关的,如下 public class ProductPriceDtoProfile: Profile { /// <su ...

  10. JAVA高级-面试题总结

    最近面试了一些公司,针对面试中遇到的问题在此记录,提升自己,造福大家 一.java源码相关 ArrayList创建和add等各种api使用原理 HashMap 的创建,put原理,和HashTable ...