最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python腳本實(shí)現(xiàn)mysql數(shù)據(jù)庫連接并插入數(shù)據(jù)

 更新時間:2026年01月08日 09:23:45   作者:Ven%  
連接MySQL數(shù)據(jù)庫并插入數(shù)據(jù)是Python中常見的任務(wù),通??梢酝ㄟ^mysql-connector-python庫來實(shí)現(xiàn),下面是一個簡單的示例腳本,有需要的小伙伴可以了解下

連接MySQL數(shù)據(jù)庫并插入數(shù)據(jù)是Python中常見的任務(wù),通??梢酝ㄟ^mysql-connector-python庫來實(shí)現(xiàn)。下面是一個簡單的示例腳本,展示了如何連接MySQL數(shù)據(jù)庫并插入數(shù)據(jù):

1.安裝mysql-connector-python庫

如果你還沒有安裝這個庫,可以通過pip安裝:

pip install mysql-connector-python

2.編寫Python腳本

下面是一個示例腳本,它連接到MySQL數(shù)據(jù)庫,創(chuàng)建一個新表(如果不存在),然后插入一些數(shù)據(jù)。

import mysql.connector
from mysql.connector import Error

try:
    # 連接到MySQL數(shù)據(jù)庫
    connection = mysql.connector.connect(
        host='localhost',       # 數(shù)據(jù)庫服務(wù)器地址
        user='your_username',   # 數(shù)據(jù)庫用戶名
        password='your_password', # 數(shù)據(jù)庫密碼
        database='your_database_name'  # 數(shù)據(jù)庫名
    )

    if connection.is_connected():
        print("Connected to MySQL database")

        # 創(chuàng)建一個cursor對象
        cursor = connection.cursor()

        # 創(chuàng)建表
        create_table_query = """
        CREATE TABLE IF NOT EXISTS employees (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(255) NOT NULL,
            salary INT,
            department VARCHAR(255)
        );
        """
        cursor.execute(create_table_query)
        print("Table created or already exists")

        # 插入數(shù)據(jù)
        insert_query = """
        INSERT INTO employees (name, salary, department)
        VALUES (%s, %s, %s);
        """
        data = ("John Doe", 70000, "Finance")
        cursor.execute(insert_query, data)
        connection.commit()
        print("Data inserted successfully")

except Error as e:
    print("Error while connecting to MySQL", e)

finally:
    # 關(guān)閉cursor和連接
    if connection.is_connected():
        cursor.close()
        connection.close()
        print("MySQL connection is closed")

3.運(yùn)行腳本

將上述腳本保存為一個.py文件,然后運(yùn)行它。確保你已經(jīng)正確設(shè)置了數(shù)據(jù)庫的連接參數(shù)(如主機(jī)、用戶名、密碼和數(shù)據(jù)庫名)。

這個腳本首先嘗試連接到MySQL數(shù)據(jù)庫,如果連接成功,它會檢查是否存在一個名為employees的表,如果不存在則創(chuàng)建這個表。然后,腳本會向這個表中插入一行數(shù)據(jù)。最后,它會關(guān)閉數(shù)據(jù)庫連接。

4.方法補(bǔ)充

python實(shí)現(xiàn)連接mysql腳本

完整代碼:

#encoding=gbk
import  sys
import  MySQLdb
 
 
conn=MySQLdb.Connection('127.0.0.1','root','123456','job',charset='gbk')
cur=conn.cursor()
cur.execute("select * from demo_jobs_store")
conn.commit()
conn.close()
 
cur.scroll(0)
row1=cur.fetchone()
print row1[3]

python腳本連接mysql數(shù)據(jù)庫的方法

下面介紹了如何利用Python的pymysql庫進(jìn)行數(shù)據(jù)庫登錄、執(zhí)行SQL查詢并獲取所有數(shù)據(jù)的過程,包括連接數(shù)據(jù)庫、執(zhí)行SQL語句、獲取查詢結(jié)果及關(guān)閉連接等關(guān)鍵步驟

完整代碼:

import pymysql
 
## 登錄賬號
host = "host_name"
user = "user_name"
password = "password"
database = "database_name"
port = port
 
conn = pymysql.connect(host, user, passwd, db, port) ## 登錄數(shù)據(jù)庫,返回連接
 
cursor = conn.cursor()
sql = "select var1, ..., varn from table_name where ..."
cursor.execute(sql)
 
data = cursor.fetchall() ##data為以元組為元素的元組
conn.commit()
cursor.close()
conn.close() ## 關(guān)閉連接

python連接mysql工具類+進(jìn)行數(shù)據(jù)驅(qū)動+配置模塊

即:將python連接mysql相關(guān)的代碼封裝起來,形成一個工具類,在需要使用的時候調(diào)用

準(zhǔn)備工作:1、key_demo——2、cases|tool——3、cases/case.py|tool/MyDB.py

1、MyDB.py工具類

# -*- coding: utf-8 -*-
# @Author  : hxy
# @Time    : 2022/1/18 15:20
# @Function:
import pymysql
 
 
class my_db:
    '''
    動作類:獲取數(shù)據(jù)連接,連接ip,端口,賬號密碼。。
    '''
 
    # 構(gòu)造函數(shù)
    def __init__(self):
        try:
            self.dbconn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='root',
                                          database='test_cases', charset='utf8')
        except Exception as e:
            print('初始化數(shù)據(jù)庫連接失敗:%s' % e)
 
    def close(self):
        self.dbconn.close()
 
    # query=查詢語句
    def select_record(self, query):
        # 查詢數(shù)據(jù)
        print('query:%s' % query)
        try:
            # 建立游標(biāo)
            db_cursor = self.dbconn.cursor()
            db_cursor.execute(query)
            result = db_cursor.fetchall()
            return result
        except Exception as e:
            print('數(shù)據(jù)庫查詢數(shù)據(jù)失?。?s' % e)
            db_cursor.close()
            exit()
 
    # 插入
    def execute_insert(self, query):
        print('query:%s' % query)
        try:
            # 建立游標(biāo)
            db_cursor = self.dbconn.cursor()
            db_cursor.execute(query)
            db_cursor.execute('commit')
            return True
        except Exception as e:
            print('數(shù)據(jù)庫插入數(shù)據(jù)失?。?s' % e)
            # 事務(wù)回滾
            db_cursor.execute('rollback')
            db_cursor.close()
            exit()

2、case.py數(shù)據(jù)驅(qū)動

# -*- coding: utf-8 -*-
# @Author  : hxy
# @Time    : 2022/1/7 15:07
# @Function:
# 針對數(shù)據(jù)庫中的數(shù)據(jù)做數(shù)據(jù)驅(qū)動
import time
import unittest
from ddt import ddt, data, unpack
 
from key_demo.tool.MyDB import my_db
 
# 必須要實(shí)例化,不然會報TypeError: select_record() missing 1 required positional argument: 'query'
testdb = my_db()
now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
 
 
@ddt
class case(unittest.TestCase):
    # @data(*my_db().select_record('select weaid,success from weather'))
    @data(*testdb.select_record('select weaid,success from weather'))
    @unpack
    def test_1(self, weaid, success):
        print(weaid, success)
        testdb.execute_insert('insert into weather(weaid,success,cre_time) values ("2","2","%s")' % now)
 
 
if __name__ == '__main__':
    unittest.main()

這樣寫的插入語句會被調(diào)用多次,要注意@data中執(zhí)行的操作具體執(zhí)行次數(shù)

換了一個寫法,先插入,再查詢

# -*- coding: utf-8 -*-
# @Author  : hxy
# @Time    : 2022/1/7 15:07
# @Function:
# 針對數(shù)據(jù)庫中的數(shù)據(jù)做數(shù)據(jù)驅(qū)動
import time
import unittest
from ddt import ddt, data, unpack
 
from key_demo.tool.MyDB import my_db
 
# 必須要實(shí)例化,不然會報TypeError: select_record() missing 1 required positional argument: 'query'
testdb = my_db()
now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
 
 
@ddt
class case(unittest.TestCase):
    # @data(*my_db().select_record('select weaid,success from weather'))
    @data(testdb.execute_insert('insert into weather(weaid,success,cre_time)values("2","2","%s")' % now))
    # @unpack
    def test_1(self,t):
        print(t)
        res = testdb.select_record('select weaid,success from weather')
        print(res)
 
 
if __name__ == '__main__':
    unittest.main()

代碼編寫的時候有幾個注意事項(xiàng):

1、只執(zhí)行一條語句,返回結(jié)果也只有一個,不需要@unpack解析

2、MyDB.py中定義有返回值,還有ddt中定義的語法return func(self, *args, **kwargs),不能缺少參數(shù)

請確保在運(yùn)行腳本之前,你的MySQL服務(wù)器正在運(yùn)行,并且你已經(jīng)正確配置了數(shù)據(jù)庫的訪問權(quán)限。

到此這篇關(guān)于Python腳本實(shí)現(xiàn)mysql數(shù)據(jù)庫連接并插入數(shù)據(jù)的文章就介紹到這了,更多相關(guān)Python腳本連接mysql內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

楚雄市| 建始县| 阿图什市| 通海县| 邓州市| 乌鲁木齐市| 新安县| 青冈县| 翁牛特旗| 丰顺县| 长泰县| 教育| 翁牛特旗| 洛阳市| 潢川县| 句容市| 上饶市| 海阳市| 和政县| 邯郸市| 博白县| 阜宁县| 全南县| 瑞丽市| 玛沁县| 嘉峪关市| 内黄县| 岑巩县| 隆化县| 桂阳县| 阜新| 东安县| 柏乡县| 景泰县| 宿迁市| 永吉县| 额济纳旗| 祁阳县| 龙山县| 宿州市| 富源县|