Python pymssql 向MSSQL数据库写入日期时间

    def insert_datetime(self):
        d = datetime.today()
        # d是日期时间对象,带微秒部分
        print(d)                            # 2022-04-08 09:10:46.181748
        print('d type:', type(d))           # d type: <class 'datetime.datetime'>

        # 将d转换为日期时间格式字符串,如果不指定参数,得到的字符串是带微秒部分的
        # 带微秒部分的字符串写入MSSQL时会报错,字符串转日期时间格式失败。
        # 所以需要指定参数 timespec="seconds" 指定转换出的字符串的时间部分保留到秒级,默认是"auto",或不指定,则保留到微秒级
        # sep=' ' 是指定转换出的字符串中,日期部分与时间部分之间的分隔符,默认是T,
        datetime_now = d.isoformat()
        print(datetime_now)                 # 2022-04-08T08:50:30.050189
        today_now = d.isoformat(sep=' ', timespec="seconds")
        print(today_now)                    # 2022-04-08 08:50:30
        print('today_now type:', type(today_now))   # today_now type: <class 'str'>

        # 此时插入MSSQL,就只需要在参数位上添加引号,不用做其他类型转换,MSSQL会自动将该字符串转为日期时间格式写入表中 前提是表字段类型是datetime
        # in_sql = """insert into test_date (test_date) values(convert(datetime, '{}', 20))""".format(today_now)
        in_sql = """insert into test_date (test_date) values('{}')""".format(today_now)
        print(in_sql)
        self.cur_his_utf.execute(in_sql)
        self.conn_his_utf.commit()

        # 以上是根据日期时间对象得到日期时间字符串,如果要自定义日期时间
        # 首先需要得到年, 月, 日, 时, 分, 秒的整数形式,然后用datetime()函数将其构造为日期时间对象
        # 得到的日期时间对象,因为只包含秒级,所以可直接用于MSSQL写入
        year = 2022
        month = 4
        day = 8
        hour = 8
        minute = 56
        second = 20
        datetime_obj = datetime(year, month, day, hour, minute, second)
        print('datetime_obj type:', type(datetime_obj))     # datetime_obj type: <class 'datetime.datetime'>
        print(datetime_obj)                                 # 2022-04-08 08:56:20
        in_sql = """insert into test_date (test_date) values('{}')""".format(datetime_obj)
        self.cur_his_utf.execute(in_sql)
        self.conn_his_utf.commit()

        # 如果只想获取到yyyy-mm-dd形式的日期对象,则使用date()函数构造,入参为年, 月, 日
        # 获取到的日期对象也可直接写入MSSQL 如果MSSQL对应字段类型是datetime,则MSSQL自动以0填充时,分,秒部分
        date_obj = date(year, month, day)
        print('date_obj type:', type(date_obj))             # <class 'datetime.date'>
        print(date_obj)                                     # 2022-04-08
        in_sql = """insert into test_date (test_date) values('{}')""".format(date_obj)
        self.cur_his_utf.execute(in_sql)
        self.conn_his_utf.commit()

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要实现Python脚本向MSSQL数据库插入语句,首先需要使用pymssql或pyodbc等库来连接数据库。以下是一个简单的示例: ```python import pymssql # 连接数据库 conn = pymssql.connect(host='localhost', user='sa', password='password', database='test') cursor = conn.cursor() # 定义插入语句 insert_query = """ INSERT INTO table_name (column1, column2, column3) VALUES (%s, %s, %s) """ # 定义要插入的值 values = ('value1', 'value2', 'value3') try: # 执行插入语句 cursor.execute(insert_query, values) # 提交事务 conn.commit() print("数据插入成功") except Exception as e: # 发生错误时回滚事务 conn.rollback() print("数据插入失败") print(str(e)) # 关闭数据库连接 conn.close() ``` 在上述示例中,我们首先使用`pymssql.connect()`方法连接到MSSQL数据库,并使用`cursor()`方法创建一个游标对象来执行SQL语句。 然后,我们定义了一个插入语句,并使用`%s`作为占位符来接受要插入的值。 接下来,我们定义了要插入的值,这里是一个包含三个值的元组。 在`try`块中,我们使用`cursor.execute()`方法执行插入语句,并使用`commit()`方法提交事务,将数据写入数据库。 如果插入过程中出现错误,我们会在`except`块中进行错误处理,并使用`rollback()`方法回滚事务,确保数据的一致性。 最后,我们使用`conn.close()`方法关闭数据库连接。 总的来说,使用Python脚本向MSSQL数据库插入语句可以通过pymssql或pyodbc等库连接数据库,执行插入语句并将数据提交到数据库
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值