Python腳本實(shí)現(xiàn)mysql數(shù)據(jù)庫(kù)連接并插入數(shù)據(jù)
連接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)文章
對(duì)python中基于tcp協(xié)議的通信(數(shù)據(jù)傳輸)實(shí)例講解
今天小編就為大家分享一篇對(duì)python中基于tcp協(xié)議的通信(數(shù)據(jù)傳輸)實(shí)例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-07-07
python實(shí)現(xiàn)用戶管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)用戶管理系統(tǒng),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01
NumPy.npy與pandas DataFrame的實(shí)例講解
今天小編就為大家分享一篇NumPy.npy與pandas DataFrame的實(shí)例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-07-07
python3.4下django集成使用xadmin后臺(tái)的方法
本篇文章主要介紹了python3.4下django集成使用xadmin后臺(tái)的方法,具有一定的參加價(jià)值,有興趣的可以了解一下2017-08-08
Python學(xué)習(xí)筆記之lambda表達(dá)式用法詳解
這篇文章主要介紹了Python學(xué)習(xí)筆記之lambda表達(dá)式用法,結(jié)合實(shí)例形式詳細(xì)分析了lambda表達(dá)式的概念、功能、原理、組成及相關(guān)使用技巧,需要的朋友可以參考下2019-08-08
python?lazypredict構(gòu)建大量基本模型簡(jiǎn)化機(jī)器學(xué)習(xí)
這篇文章主要介紹了python?lazypredict構(gòu)建大量基本模型簡(jiǎn)化機(jī)器學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01
Python numpy實(shí)現(xiàn)數(shù)組合并實(shí)例(vstack,hstack)
這篇文章主要介紹了Python numpy實(shí)現(xiàn)數(shù)組合并(官網(wǎng)實(shí)例),涉及vstack,hstack的簡(jiǎn)單用法,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01
Python定義一個(gè)跨越多行的字符串的多種方法小結(jié)
今天小編就為大家分享一篇Python定義一個(gè)跨越多行的字符串的多種方法小結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-07-07
Python tensorflow與pytorch的浮點(diǎn)運(yùn)算數(shù)如何計(jì)算
這篇文章主要介紹了Python tensorflow與pytorch的浮點(diǎn)運(yùn)算數(shù)如何計(jì)算,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2022-11-11

