1. 程式人生 > >Python基礎(二)--- IDEA中整合Python和MySQL,使用Python進行SQL操作

Python基礎(二)--- IDEA中整合Python和MySQL,使用Python進行SQL操作

一、Python操作MySQL
-----------------------------------------------------
    1.安裝MySQL

    2.安裝mysql的python模組
        a.下載並安裝PyMySQL-master.zip
        https://github.com/PyMySQL/PyMySQL

    3.解壓,在解壓目錄下,進入cmd,執行安裝命令
        cmd> python setup.py install

    4.重啟idea

    5.建立python檔案,測試是否連線
        
import pymysql

        print("================測試是否連通====================")
        try:
            conn = pymysql.connect(host='localhost', user='mysql', passwd='mysql', db='python', port=3306, charset='utf8')
            cur = conn.cursor()
            cur.execute('select version()')
            version = cur.fetchone()
            print(version)
            cur.close()
            conn.close()
        except  Exception:
            print("發生異常")

        ================測試是否連通====================
        ('5.5.60',)


二、使用Python進行SQL操作
--------------------------------------------------------------------------
    1.create and Drop Table
        
# print("================ Drop Table====================")
        # try:
        #     conn = pymysql.connect(host='localhost', user='mysql', passwd='mysql', db='python', port=3306, charset='utf8')
        #     cur = conn.cursor()
        #     cur.execute('drop table t1')
        #     cur.close()
        #     conn.close()
        # except  Exception:
        #     print("發生異常")

        # print("================ Create Table====================")
        # try:
        #     conn = pymysql.connect(host='localhost', user='mysql', passwd='mysql', db='python', port=3306, charset='utf8')
        #     cur = conn.cursor()
        #     cur.execute('create table t1(id int primary key auto_increment, name varchar (20), age int)')
        #     conn.commit()
        #     cur.close()
        #     conn.close()
        # except  Exception:
        #     print("發生異常")

    2.insert into
        --------------------------------------------------------------------
        
print("================ Insert 插入 ====================")
        try:
            # 開啟連線
            conn = pymysql.connect(host = "localhost", user = "mysql", passwd= "mysql",db = "python",port = 3306,charset="utf8");
            # 開啟遊標
            cur = conn.cursor();
            # 開始插入
            sql = "insert into t1 (name,age) values ('%s','%d')" %('tom',12);
            cur.execute(sql);
            conn.commit();
            cur.close()
            conn.close()

        except Exception:
            print("發生異常")

        ----------------------------------------------------------------------------------------
        
print("================ Insert 插入10000條記錄 ====================")
        print("================ 帶提交和回滾機制 ====================")
        try:
            # 開啟連線
            conn = pymysql.connect(host='localhost', user='mysql', passwd='mysql', db='python', port=3306, charset='utf8')
            # 開啟遊標
            cur = conn.cursor()
            # 關閉自動提交
            conn.autocommit(False);
            #執行sql
            i = 0 ;
            while i < 10000 :
                sql = "insert into t1(name,age) values('%s',%d)" % ("tom" + str(i),i % 100);
                #異常回滾測試
                if(i == 50):
                    sql = "insert"
                #執行sql插入
                cur.execute(sql)
                i += 1 ;
            #提交
            conn.commit()

        except Exception:
            print("發生異常,進行回滾操作")
            conn.rollback()

        finally:
            #關閉
            cur.close()
            conn.close()

    3.delect from
       
 print("================ Delete====================")
        try:
            # 開啟連線
            conn = pymysql.connect(host='localhost', user='mysql', passwd='mysql', db='python', port=3306, charset='utf8')
            # 開啟遊標
            cur = conn.cursor()
            # 關閉自動提交
            conn.autocommit(False);
            #執行sql
            sql = "delete from t1 where id > 50";
            cur.execute(sql)
            #提交
            conn.commit()

        except Exception:
            print("發生異常,進行回滾操作")
            conn.rollback()

        finally:
            #關閉
            cur.close()
            conn.close()

    4.update set
        
print("================ Update ====================")
        try:
            # 開啟連線
            conn = pymysql.connect(host='localhost', user='mysql', passwd='mysql', db='python', port=3306, charset='utf8')
            # 開啟遊標
            cur = conn.cursor()
            # 關閉自動提交
            conn.autocommit(False);
            #執行sql
            sql = "update t1 set age = age - 20 where age > 20";
            cur.execute(sql)
            #提交
            conn.commit()

        except Exception:
            print("發生異常,進行回滾操作")
            conn.rollback()

        finally:
            #關閉
            cur.close()
            conn.close()
    5.select from
       
 print("================ select from ====================")
        try:
            # 開啟連線
            conn = pymysql.connect(host='localhost', user='mysql', passwd='mysql', db='python', port=3306, charset='utf8')
            # 開啟遊標
            cur = conn.cursor()
            # 關閉自動提交
            conn.autocommit(False);
            #執行sql
            sql = "select * from t1";
            cur.execute(sql)
            res = cur.fetchall()
            for r in res :
                print(str(r[0]) + "," + r[1] + "," + str(r[2]));
            #提交
            conn.commit()

        except Exception:
            print("發生異常,進行回滾操作")
            conn.rollback()

        finally:
            #關閉
            cur.close()
            conn.close()

    6.select count(*)
       
 print("================ select count(*) from ====================")
        try:
            # 開啟連線
            conn = pymysql.connect(host='localhost', user='mysql', passwd='mysql', db='python', port=3306, charset='utf8')
            # 開啟遊標
            cur = conn.cursor()
            # 關閉自動提交
            conn.autocommit(False);
            #執行sql
            sql = "select count(*) from t1 where id > 10";
            cur.execute(sql)
            res = cur.fetchone()
            print(res[0])
            #提交
            conn.commit()

        except Exception:
            print("發生異常,進行回滾操作")
            conn.rollback()

        finally:
            #關閉
            cur.close()
            conn.close()


    7.呼叫Mysql中的函式
        
print("================ 呼叫Mysql的函式 ====================")
        try:
            # 開啟連線
            conn = pymysql.connect(host='localhost', user='mysql', passwd='mysql', db='python', port=3306, charset='utf8')
            # 開啟遊標
            cur = conn.cursor()
            # 關閉自動提交
            conn.autocommit(False);
            #執行sql
            sql = "call mydata.up_add(1,2,@q);";
            cur.execute(sql)
            cur.execute("select @q");
            res = cur.fetchone()
            print(res[0])
            conn.commit()
            #提交

        except Exception:
            print("發生異常,進行回滾操作")
            conn.rollback()

        finally:
            #關閉
            cur.close()
            conn.close()

    8.呼叫Mysql中的儲存過程
       

 print("================ 呼叫Mysql的儲存過程 ====================")
        try:
            # 開啟連線
            conn = pymysql.connect(host='localhost', user='mysql', passwd='mysql', db='mydata', port=3306, charset='utf8')
            # 開啟遊標
            cur = conn.cursor()
            # 關閉自動提交
            conn.autocommit(False);
            #建立表
            sql = "create table mytable(id int primary key auto_increment, name varchar(20), password varchar(20), age int)";
            cur.execute(sql)
            #執行儲存過程
            cur.execute("call big_insert2(100)");
            #查詢
            sql = "select * from mytable";
            cur.execute(sql)

            res = cur.fetchall()
            for r in res:
                print(str(r[0]) + "," + str(r[1]) + "," +str(r[2]) + "," +str(r[3]))
            conn.commit()
            #提交

        except Exception:
            print("發生異常,進行回滾操作")
            conn.rollback()

        finally:
            #關閉
            cur.close()
            conn.close()