Python脚本实现mysql数据库连接并插入数据

 更新时间:2026年01月08日 09:23:45   作者:Ven%  
连接MySQL数据库并插入数据是Python中常见的任务,通常可以通过mysql-connector-python库来实现,下面是一个简单的示例脚本,有需要的小伙伴可以了解下

连接MySQL数据库并插入数据是Python中常见的任务,通常可以通过mysql-connector-python库来实现。下面是一个简单的示例脚本,展示了如何连接MySQL数据库并插入数据:

1.安装mysql-connector-python库

如果你还没有安装这个库,可以通过pip安装:

pip install mysql-connector-python

2.编写Python脚本

下面是一个示例脚本,它连接到MySQL数据库,创建一个新表(如果不存在),然后插入一些数据。

import mysql.connector
from mysql.connector import Error

try:
    # 连接到MySQL数据库
    connection = mysql.connector.connect(
        host='localhost',       # 数据库服务器地址
        user='your_username',   # 数据库用户名
        password='your_password', # 数据库密码
        database='your_database_name'  # 数据库名
    )

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

        # 创建一个cursor对象
        cursor = connection.cursor()

        # 创建表
        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")

        # 插入数据
        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:
    # 关闭cursor和连接
    if connection.is_connected():
        cursor.close()
        connection.close()
        print("MySQL connection is closed")

3.运行脚本

将上述脚本保存为一个.py文件,然后运行它。确保你已经正确设置了数据库的连接参数(如主机、用户名、密码和数据库名)。

这个脚本首先尝试连接到MySQL数据库,如果连接成功,它会检查是否存在一个名为employees的表,如果不存在则创建这个表。然后,脚本会向这个表中插入一行数据。最后,它会关闭数据库连接。

4.方法补充

python实现连接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数据库的方法

下面介绍了如何利用Python的pymysql库进行数据库登录、执行SQL查询并获取所有数据的过程,包括连接数据库、执行SQL语句、获取查询结果及关闭连接等关键步骤

完整代码:

import pymysql
 
## 登录账号
host = "host_name"
user = "user_name"
password = "password"
database = "database_name"
port = port
 
conn = pymysql.connect(host, user, passwd, db, port) ## 登录数据库,返回连接
 
cursor = conn.cursor()
sql = "select var1, ..., varn from table_name where ..."
cursor.execute(sql)
 
data = cursor.fetchall() ##data为以元组为元素的元组
conn.commit()
cursor.close()
conn.close() ## 关闭连接

python连接mysql工具类+进行数据驱动+配置模块

即:将python连接mysql相关的代码封装起来,形成一个工具类,在需要使用的时候调用

准备工作: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:
    '''
    动作类:获取数据连接,连接ip,端口,账号密码。。
    '''
 
    # 构造函数
    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('初始化数据库连接失败:%s' % e)
 
    def close(self):
        self.dbconn.close()
 
    # query=查询语句
    def select_record(self, query):
        # 查询数据
        print('query:%s' % query)
        try:
            # 建立游标
            db_cursor = self.dbconn.cursor()
            db_cursor.execute(query)
            result = db_cursor.fetchall()
            return result
        except Exception as e:
            print('数据库查询数据失败:%s' % e)
            db_cursor.close()
            exit()
 
    # 插入
    def execute_insert(self, query):
        print('query:%s' % query)
        try:
            # 建立游标
            db_cursor = self.dbconn.cursor()
            db_cursor.execute(query)
            db_cursor.execute('commit')
            return True
        except Exception as e:
            print('数据库插入数据失败:%s' % e)
            # 事务回滚
            db_cursor.execute('rollback')
            db_cursor.close()
            exit()

2、case.py数据驱动

# -*- coding: utf-8 -*-
# @Author  : hxy
# @Time    : 2022/1/7 15:07
# @Function:
# 针对数据库中的数据做数据驱动
import time
import unittest
from ddt import ddt, data, unpack
 
from key_demo.tool.MyDB import my_db
 
# 必须要实例化,不然会报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()

这样写的插入语句会被调用多次,要注意@data中执行的操作具体执行次数

换了一个写法,先插入,再查询

# -*- coding: utf-8 -*-
# @Author  : hxy
# @Time    : 2022/1/7 15:07
# @Function:
# 针对数据库中的数据做数据驱动
import time
import unittest
from ddt import ddt, data, unpack
 
from key_demo.tool.MyDB import my_db
 
# 必须要实例化,不然会报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()

代码编写的时候有几个注意事项:

1、只执行一条语句,返回结果也只有一个,不需要@unpack解析

2、MyDB.py中定义有返回值,还有ddt中定义的语法return func(self, *args, **kwargs),不能缺少参数

请确保在运行脚本之前,你的MySQL服务器正在运行,并且你已经正确配置了数据库的访问权限。

到此这篇关于Python脚本实现mysql数据库连接并插入数据的文章就介绍到这了,更多相关Python脚本连接mysql内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 详细介绍Python中的偏函数

    详细介绍Python中的偏函数

    这篇文章主要介绍了Python中的偏函数,示例代码基于Python2.x版本,需要的朋友可以参考下
    2015-04-04
  • Python 中将值附加到集合的操作方法

    Python 中将值附加到集合的操作方法

    这篇文章主要介绍了Python 中将值附加到集合的操作方法,通过使用 add() 方法或 update() 方法,你可以向 Python 中的集合中添加元素,在添加元素时,需要注意不允许重复元素和集合是无序的,本文通过示例代码给大家介绍的非常详细,需要的朋友可以参考下
    2023-05-05
  • Python2实现的图片文本识别功能详解

    Python2实现的图片文本识别功能详解

    这篇文章主要介绍了Python2实现的图片文本识别功能,结合实例形式分析了Python pytesser库的安装及使用pytesser库识别图片文字相关操作技巧,需要的朋友可以参考下
    2018-07-07
  • MAC中PyCharm设置python3解释器

    MAC中PyCharm设置python3解释器

    本文给大家分享的是修改MACA中pycharm的默认的Python解释器,由于默认解释器是Python2,使用起来各种不便,下面给大家讲解下如何修改
    2017-12-12
  • Python Generator生成器函数基本概念及高级用途技巧示例

    Python Generator生成器函数基本概念及高级用途技巧示例

    这篇文章主要为大家介绍了Python Generator生成器函数基本概念及高级用途技巧示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-12-12
  • pandas 数据透视和逆透视的实现

    pandas 数据透视和逆透视的实现

    本文介绍了pandas 数据透视和逆透视的实现,包含pivot()方法透视及pivot_table()方法逆透视,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧
    2024-12-12
  • python聊天程序实例代码分享

    python聊天程序实例代码分享

    这篇文章主要介绍了用python写的聊天程序,开两个线程,即是客户端,也是服务器,大家可以参考使用
    2013-11-11
  • JSONLINT:python的json数据验证库实例解析

    JSONLINT:python的json数据验证库实例解析

    本文介绍的 jsonlint 启发自 python 的表单验证工具 wtforms,wtforms 通过继承 Form 类也能进行 json 数据验证,下面通过一些例子给大家详细介绍,非常不错,具有参考借鉴价值,需要的朋友参考下吧
    2017-11-11
  • Python基础之常用库常用方法整理

    Python基础之常用库常用方法整理

    这篇文章主要介绍了Python基础之常用库常用方法整理,文中有非常详细的代码示例,对正在学习python基础的小伙伴们有非常好的帮助,需要的朋友可以参考下
    2021-04-04
  • python的mysqldb安装步骤详解

    python的mysqldb安装步骤详解

    这篇文章主要介绍了python的mysqldb安装步骤详解的相关资料,这里提供实现的具体步骤,需要的朋友可以参考下
    2017-08-08

最新评论