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

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

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

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

1.安裝mysql-connector-python庫(kù)

如果你還沒有安裝這個(gè)庫(kù),可以通過(guò)pip安裝:

pip install mysql-connector-python

2.編寫Python腳本

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

import mysql.connector
from mysql.connector import Error

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

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

        # 創(chuàng)建一個(gè)cursor對(duì)象
        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)行腳本

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

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

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ù)庫(kù)的方法

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

完整代碼:

import pymysql
 
## 登錄賬號(hào)
host = "host_name"
user = "user_name"
password = "password"
database = "database_name"
port = port
 
conn = pymysql.connect(host, user, passwd, db, port) ## 登錄數(shù)據(jù)庫(kù),返回連接
 
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ū)動(dòng)+配置模塊

即:將python連接mysql相關(guān)的代碼封裝起來(lái),形成一個(gè)工具類,在需要使用的時(shí)候調(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:
    '''
    動(dòng)作類:獲取數(shù)據(jù)連接,連接ip,端口,賬號(hào)密碼。。
    '''
 
    # 構(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ù)庫(kù)連接失?。?s' % e)
 
    def close(self):
        self.dbconn.close()
 
    # query=查詢語(yǔ)句
    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ù)庫(kù)查詢數(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ù)庫(kù)插入數(shù)據(jù)失?。?s' % e)
            # 事務(wù)回滾
            db_cursor.execute('rollback')
            db_cursor.close()
            exit()

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

# -*- coding: utf-8 -*-
# @Author  : hxy
# @Time    : 2022/1/7 15:07
# @Function:
# 針對(duì)數(shù)據(jù)庫(kù)中的數(shù)據(jù)做數(shù)據(jù)驅(qū)動(dòng)
import time
import unittest
from ddt import ddt, data, unpack
 
from key_demo.tool.MyDB import my_db
 
# 必須要實(shí)例化,不然會(huì)報(bào)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()

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

換了一個(gè)寫法,先插入,再查詢

# -*- coding: utf-8 -*-
# @Author  : hxy
# @Time    : 2022/1/7 15:07
# @Function:
# 針對(duì)數(shù)據(jù)庫(kù)中的數(shù)據(jù)做數(shù)據(jù)驅(qū)動(dòng)
import time
import unittest
from ddt import ddt, data, unpack
 
from key_demo.tool.MyDB import my_db
 
# 必須要實(shí)例化,不然會(huì)報(bào)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()

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

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

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

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

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

相關(guān)文章

最新評(píng)論

凤庆县| 涟源市| 城步| 昌黎县| 光山县| 文昌市| 丰城市| 哈巴河县| 鄯善县| 彝良县| 贵溪市| 佛坪县| 建始县| 临泉县| 恩平市| 宁晋县| 沁阳市| 永善县| 汽车| 广宁县| 平和县| 富裕县| 莱阳市| 溧阳市| 崇州市| 寻甸| 石棉县| 和田市| 密云县| 日照市| 赤壁市| 太白县| 清丰县| 柯坪县| 基隆市| 黄石市| 将乐县| 濉溪县| 海阳市| 德清县| 阿克|