이전에 Python으로 mysql 데이터를 쿼리하는 방법에 대한 글을 쓴 적이 있습니다. 오늘은 Python을 통해 mysql 데이터베이스에 데이터를 삽입하는 방법에 대해 작성해 보겠습니다.
추천 mysql 비디오 튜토리얼: "mysql 튜토리얼"
먼저 Python에서 데이터베이스, 테이블, 사용자
mysql> create database top_ten; mysql> use top_ten mysql> create table log (id int PRIMARY KEY AUTO_INCREMENT, ip char(20), url char(30), status int, total int) charset=utf8; mysql> create user 'bob'@'10.200.42.52' identified by 'talent'; mysql> desc log; +--------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------+-------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | ip | char(20) | YES | | NULL | | | url | char(30) | YES | | NULL | | | status | int(11) | YES | | NULL | | | total | int(11) | YES | | NULL | | +--------+-------------+------+-----+---------+----------------+ mysql> grant all on top_ten.* to bob@localhost identified by 'talent'; mysql> flush privileges;
를 구축하세요. 테스트를 위한 문 삽입
>>> import MySQLdb >>> db = MySQLdb.connect(host='localhost',user='bob',passwd='talent',db='top_ten',port=3306, charset='utf8') >>> db.autocommit(True) >>> cursor = db.cursor() >>> sql = "insert into log(ip, url, status, total) values('1.1.1.1', 'http', '200', '66')" >>> cursor.execute(sql) 1L >>> sql = "insert into log(ip, url, status, total) values('2.2.2.2', 'http', '200', '66')" >>> cursor.execute(sql) 1L #只能查询一条结果 >>> cursor.execute('select * from log') 1L >>> cursor.fetchone() (1L, u'1.1.1.1', u'http', 200L, 66L) #查询所有数据,然后一条条获取结果 >>> cursor.execute('select * from log') 2L >>> cursor.fetchmany() ((1L, u'1.1.1.1', u'http', 200L, 66L),) >>> cursor.fetchmany() ((2L, u'2.2.2.2', u'http', 200L, 66L),) >>> cursor.fetchmany() () #查询所有数据,一个元组显示所有结果 >>> cursor.execute('select * from log') 2L >>> cursor.fetchall() ((1L, u'1.1.1.1', u'http', 200L, 66L), (2L, u'2.2.2.2', u'http', 200L, 66L))
스크립트 삽입
[root@python ~]# mysql_insert.py #!/usr/bin/env python # -*- coding: utf-8 -*- ''' Date:2017-03-28 Author:Bob ''' import MySQLdb def mysql_insert(): #Open the database connection db = MySQLdb.connect(host='localhost',user='bob',passwd='talent',db='top_ten',port=3306, charset='utf8') #Automatic submission db.autocommit(True) #Gets the operation cursor cursor = db.cursor() with open('access_log-20170217', 'r') as f: res = {} #Get ip, url, status for line in f.readlines(): line = line.split(' ') ip = line[0] url = line[6] status = line[8] #print ip, url, status #ip, url, status as key, each time plus 1 res[(ip, url, status)] = res.get((ip, url, status),0)+1 #Generate a list res_list = [(k[0],k[1],k[2],v) for k,v in res.items()] # Print the top ten lines #for k in sorted(res_list,key=lambda x:x[3],reverse=True)[:10]: #print k #SQL statement inserted for i in res_list: #print i sql = "insert into log(ip, url, status, total) values('%s', '%s', '%s', '%s')" %(i[0], i[1], i[2], i[3]) try: #Execute the SQL statement cursor.execute(sql) except Exception as e: print "Error: ", e #Close the cursor cursor.close() #Close the database connection db.close() if __name__ == '__main__': mysql_insert()
스크립트 실행
[root@python ~]# python mysql_insert.py
쿼리 검증
mysql> select * from log; +----+----------------+---------------------------+--------+-------+ | id | ip | url | status | total | +----+----------------+---------------------------+--------+-------+ | 1 | 1.1.1.1 | http | 200 | 66 | | 2 | 2.2.2.2 | http | 200 | 66 | | 3 | 10.200.56.80 | /api/sshpasswd/ | 200 | 1 | | 4 | 10.201.201.82 | /business/add | 200 | 20 | | 5 | 10.200.56.80 | / | 403 | 1 | | 6 | 10.200.56.80 | /account/login?next=%2F | 200 | 1 | | 7 | 10.200.56.80 | /icons/apache_pb.gif | 200 | 1 | | 8 | 10.200.56.80 | /icons/unknown.gif | 200 | 1 | | 9 | 127.0.0.1 | / | 403 | 1 | | 10 | 10.200.56.80 | /account/login_auth | 200 | 1 | | 11 | 10.200.56.80 | /static/js/echarts.min.js | 304 | 1 | | 12 | 10.200.56.80 | /business/collist | 200 | 2 | | 13 | 10.200.56.80 | /business/chlist | 200 | 1 | | 14 | 10.200.56.80 | / | 200 | 1 | | 15 | 10.200.56.80 | /icons/text.gif | 200 | 1 | | 16 | 10.200.56.80 | /icons/poweredby.png | 200 | 1 | | 17 | 10.200.42.50 | /host/addscan | 200 | 1 | | 18 | 10.200.56.80 | /icons/blank.gif | 200 | 1 | | 19 | 10.200.56.80 | / | 302 | 1 | | 20 | 10.200.56.80 | /icons/back.gif | 200 | 1 | | 21 | 10.200.56.80 | /account/is_activate | 200 | 1 | | 22 | 10.200.56.80 | /favicon.ico | 404 | 4 | | 23 | 61.159.140.123 | /favicon.ico | 404 | 4 | +----+----------------+---------------------------+--------+-------+ 23 rows in set (0.00 sec)
테스트 데이터
61.159.140.123 - - [16/Feb/2017:14:45:39 +0800] "GET /api/sshpasswd/ HTTP/1.1" 200 1338 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0" 61.159.140.123 - - [16/Feb/2017:14:45:39 +0800] "GET /icons/text.gif HTTP/1.1" 200 229 "http://10.200.42.52/" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0" 61.159.140.123 - - [16/Feb/2017:14:45:39 +0800] "GET /icons/unknown.gif HTTP/1.1" 200 245 "http://10.200.42.52/" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0"
위 내용은 Python은 mysql을 작동하여 데이터를 삽입합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Pythonusesahybridmodelofilationandlostretation : 1) ThePyThoninterPretreCeterCompileSsourcodeIntOplatform-IndependentBecode.

Pythonisbothingretedandcompiled.1) 1) it 'scompiledtobytecodeforportabilityacrossplatforms.2) thebytecodeisthentenningreted, withfordiNamictyTeNgreted, WhithItmayBowerShiledlanguges.

forloopsareusedwhendumberofitessiskNowninadvance, whilewhiloopsareusedwhentheationsdepernationsorarrays.2) whiloopsureatableforscenarioScontiLaspecOndCond

pythonisnotpurelynlogreted; itusesahybrideprophorfbyodecodecompilationandruntime -INGRETATION.1) pythoncompilessourcecodeintobytecode, thepythonVirtualMachine (pvm)

ToconcatenatelistsinpythonwithesameElements, 사용 : 1) OperatorTokeEpduplicates, 2) asettoremovedUplicates, or3) listComperensionForControlOverDuplicates, 각 methodHasDifferentPerferformanCeanDorderImpestications.

PythonisancerpretedLanguage, 비판적 요소를 제시하는 PytherfaceLockelimitationsIncriticalApplications.1) 해석 된 언어와 같은 thePeedBackandbackandrapidProtoTyping.2) CompilledlanguagesLikec/C transformt 해석

useforloopswhhenmerfiterationsiskNownInAdvance 및 WhileLoopSweHeniTesslationsDepoyConditionismet whilEroopsSuitsCenarioswhereTheLoopScenarioswhereTheLoopScenarioswhereTheLoopScenarioswhereTherInatismet, 유용한 광고 인 푸트 gorit


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!

드림위버 CS6
시각적 웹 개발 도구

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는