日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

第一节、Alex 讲解 python+mysql 交互;

發布時間:2024/9/5 数据库 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 第一节、Alex 讲解 python+mysql 交互; 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Python Mysql 交互
A、Alex 的語法展示:import MySQLdb?try:conn=MySQL.connect(host='localhost',user='root',passwod='123qwe',db='test-DB',port='3306')cur?=conn.cursor()cur.execute('select * from user_info')? ? ?cur.close()? ? ?conn.close()except MySQLdb.Errot,e:? ? ?print 'Mysql Error ?Msg:' , e?B、例子:例子1、獲取數據
  • # 打開數據庫連接
  • db = MySQLdb.connect("localhost","root","123qwe","host_list" )

  • # 使用cursor()方法獲取操作游標?
  • cursor = db.cursor()
  • # 使用execute方法執行SQL語句
  • cursor.execute("SELECT VERSION()")
  • # 使用 fetchone() 方法獲取一條數據庫。【以-行計數】
  • data = cursor.fetchone()
  • print "Database version : %s " % data
  • # 關閉數據庫連接
  • db.close()

  • 2、插去數據;
  • # 創建數據表SQL語句

  • sql = """CREATE TABLE EMPLOYEE ( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )"""

  • try:
  • # 執行sql語句
  • cursor.execute(sql)

  • # 提交到數據庫執行
  • db.commit()
  • except:
  • # Rollback in case there is any error
  • db.rollback()

  • 常用函數:注意這個 commit( ) 提交rollback( ) 回滾


    (二)、插去多條數據。
  • #!/usr/bin/python
  • #coding:utf-8
  • try:
  • import MySQLdb
  • db = MySQLdb.connect("localhost","root","123qwe","host_list" )
  • cursor = db.cursor()
  • v_list = []
  • for i in range(10):
  • v_list.append(("linux%s" %i,"moban%s" %i,"12%s" %i,"M", "2000"))
  • print v_list
  • cursor.executemany( "INSERT INTO EMPLOYEE \
  • VALUES (%s, %s, %s, %s, %s)", v_list)
  • cursor.close()
  • db.commit()
  • db.close()
  • except MySQLdb.Error,e:
  • print 'Mysql Error Msg:',e
  • 執行結果:

    查詢數據庫的結果:



    例子展示:
    釋義:cur.scroll(3,mode="relative") ? # ?光標相對的移動到 第三行;cur.scroll(0,mode='absolute') ?print cur.fetchone ( ) ? ? ? ? ? ? ? ?# ?取一行內容;從當前游標處。print cur.fetchall( ) ? ? ? ? ? ? ? ? ? ?#從當前位置取全部的行;ps: 默認的 是從 0行開始的, ??
    執行結果后:





    來自為知筆記(Wiz)

    轉載于:https://www.cnblogs.com/zhangju/p/5720211.html

    總結

    以上是生活随笔為你收集整理的第一节、Alex 讲解 python+mysql 交互;的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。