検索
ホームページバックエンド開発Python チュートリアルPythonはmysqlを操作してデータを挿入します

以前、Python で mysql データをクエリすることについての記事を書きました。今日は、Python を介して mysql データベースにデータを挿入する方法について書きます。

推奨される関連する mysql ビデオ チュートリアル: "mysql チュートリアル"

まずデータベースを構築し、テーブルを作成し、ユーザーを作成します

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;

テストのために Python の下にステートメントを挿入します

>>> 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 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
Python:編集と解釈に深く掘り下げますPython:編集と解釈に深く掘り下げますMay 12, 2025 am 12:14 AM

pythonusesahybridmodelofcompilation andtertation:1)thepythoninterpretercompilessourcodeodeplatform-indopent bytecode.2)thepythonvirtualmachine(pvm)thenexecuteTesthisbytecode、balancingeaseoputhswithporformance。

Pythonは解釈されたものですか、それとも編集された言語であり、なぜそれが重要なのですか?Pythonは解釈されたものですか、それとも編集された言語であり、なぜそれが重要なのですか?May 12, 2025 am 12:09 AM

pythonisbothintersedand compiled.1)it'scompiledtobytecode forportabalityacrossplatforms.2)bytecodeisthenは解釈され、開発を許可します。

ループ対pythonのループの場合:説明されたキーの違いループ対pythonのループの場合:説明されたキーの違いMay 12, 2025 am 12:08 AM

loopsareideal whenyouwhenyouknumberofiterationsinadvance、foreleloopsarebetterforsituationsは、loopsaremoreedilaConditionismetを使用します

ループのために:実用的なガイドループのために:実用的なガイドMay 12, 2025 am 12:07 AM

henthenumber ofiterationsisknown advanceの場合、dopendonacondition.1)forloopsareideal foriterating over for -for -for -saredaverseversives likelistorarrays.2)whileopsaresupasiable forsaresutable forscenarioswheretheloopcontinupcontinuspificcond

Python:それは本当に解釈されていますか?神話を暴くPython:それは本当に解釈されていますか?神話を暴くMay 12, 2025 am 12:05 AM

pythonisnotpurelyLepted; itusesahybridapproachofbytecodecodecodecodecodecodedruntimerttation.1)pythoncompilessourcodeintobytecode、whodythepythonvirtualmachine(pvm).2)

同じ要素を持つPython Concatenateリスト同じ要素を持つPython ConcatenateリストMay 11, 2025 am 12:08 AM

ToconcatenateListsinpythothesheElements、使用:1)Operatortokeepduplicates、2)asettoremoveduplicates、or3)listcomplunting for controloverduplicates、各メトドハスディフェルフェルフェントパフォーマンスアンドソーダーインプリテーション。

解釈対編集言語:Pythonの場所解釈対編集言語:Pythonの場所May 11, 2025 am 12:07 AM

pythonisantertedlanguage、useaseofuseandflexibility-butfactingporformantationationsincriticalapplications.1)解釈されたlikepythonexecuteline-by-lineを解釈します

ループのために:Pythonでそれぞれを使用するのはいつですか?ループのために:Pythonでそれぞれを使用するのはいつですか?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance、andwhiloopswheniterationsdependonacondition.1)forloopsareidealforsecenceslikelistoranges.2)

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

AtomエディタMac版ダウンロード

AtomエディタMac版ダウンロード

最も人気のあるオープンソースエディター

SublimeText3 英語版

SublimeText3 英語版

推奨: Win バージョン、コードプロンプトをサポート!

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

EditPlus 中国語クラック版

EditPlus 中国語クラック版

サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

DVWA

DVWA

Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、