编写一个程序,接收两个参数ID和content
(1)如果这ID在文件IDlist.txt中有,那么在数据库中插入一条记录。
(2)如果ID没有那么把ID和content写入文件result.txt中。
[root@oldboy ~]# cat IDlist.txt 01 ydds 02 jeacen 03 kuqi 04 maidong 05 yazhe 06 maliao 07 xiaofan
这道题目,逻辑还是存在点问题,只有insert操作,而没有update
shell编程答案,参考老男的答案:
#!/bin/sh Idarray=($(cat $3|awk '{print $1}')) status=0 for ((i=0; i<`echo ${#Idarray[*]}`; i++)) do echo ${Idarray[$i]} if [ $1 -eq ${Idarray[$i]} ] ;then mysql -h192.168.1.*** -P3308 -uroot -p*** opstest -e "DROP DATABASE IF EXISTS oldboy;" mysql -h192.168.1.*** -P3308 -uroot -p*** opstest -e "create database oldboy;create table oldboy.oldboy(id int,content varchar(100))" mysql -h192.168.1.*** -P3308 -uroot -p*** opstest -e "insert into opstest.test01 values($1,'$2')" status+=99 fi done if [ $status -ne 99 ];then echo "$1 $2 $3" > ./result.txt fi
python实现方式:
# coding: utf-8 import sys import MySQLdb ID = sys.argv[ 1 ] content = sys.argv[ 2 ] IDListFile = sys.argv[ 3 ] def demo(IDListFile,raw_num,raw_content): status = 0 files = file (IDListFile, 'r' ) lines = files.readlines() for item in lines: if item != " \n " : IDs = item.split( " " ) ID = IDs[ 0 ] if ID == raw_num: conn=MySQLdb.connect( host = '192.168.1.***' , user = 'root' , passwd = 'U_8***' , db = 'opstest' , port = 3308 ) cur=conn.cursor() value = [ID,raw_content] cur.execute( 'insert into opstest.test01 values(%s,%s)' ,value) conn.commit() cur.close() conn.close() status += 99 if status != 99 : insert_file = file ( "/tmp/result.txt" , "a" ) insert_file.write( "%s %s %s" %(raw_num,raw_content,IDListFile)) if __name__ == "__main__" : #demo("/tmp/IDlist.txt", "07" ,"abcd") demo(IDListFile,ID,content)