首页 > 数据库 >6.Python操作数据库

6.Python操作数据库

时间:2024-03-11 22:35:33浏览次数:20  
标签:cur Python 数据库 cursor result 操作 self conn

1.操作mysql数据库

import pymysql

# 连接数据库
conn=pymysql.connect(host="127.0.0.1",port=3306,user="root",password="123456",database="a",autocommit=True)

# 创建游标进行数据库操作以及获取数据
cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)

# 执行sql语句,并返回影响的行数
# cursor.execute("""insert into user(username,password,email) values(%s,%s,%s)""",("haha","7890","[email protected]",))
# 插入多条数据
# row=cursor.executemany("""insert into user(username,password,email) values(%s,%s,%s)""",[("haha","7890","[email protected]",),("gg","7890","[email protected]",)])

# 查询数据
cursor.execute("select * from user")
# fetchone返回一条数据,类型是字典
result=cursor.fetchone()
print(type(result),result)

# fetchmany返回多条数据,数据展示是列表里面包含字典
result=cursor.fetchmany(3)
print(type(result),result)

# fetchmany返回多条数据,数据展示是列表里面包含字典
result=cursor.fetchall()
print(type(result),result)

# 提交数据
# conn.commit()

# 关闭游标
cursor.close()

# 关闭数据库连接
conn.close()

 2.操作oracle数据库

import cx_Oracle

# 创建数据库连接的类
class connDataBase():
    def __init__(self,userName,password,tns):
        self._userName=userName
        self._password=password
        self._tns=tns
        self.conn,self.cur=self.conn()
     
    #  创建数据库连接
    def conn(self):
        try:
            conn=cx_Oracle.Connection(self._userName,self._password,self._tns)
            cur=conn.cursor()
            return conn,cur
        except Exception as e:
            print("连接数据库出错",e)
            return False
        
    #     增删改数据
    def dealData(self,sql):
        try:
            self.cur.excute(sql)
            self.cur.commit()
        except Exception as e:
            print("处理数据出错")
     
    # 查询数据
    def queryData(self,sql,num="Many"):
        rs=""
        try:
            self.cur.excute(sql)
        except Exception as e:
            print("查询数据出错",e)
            return False
        if num=="Many":
            rs=self.cur.fetchall()
        else:
            rs=self.cur.fetchone()
        return rs
    
    def deleteCur(self):
        self.cur.close()
        self.conn.close()

3.操作cassandra数据库

from cassandra import ConsistencyLevel
from cassandra.cluster import Cluster
from cassandra.auth import PlainTextAuthProvider
from cassandra.query import SimpleStatement

def connCassandra(cql):
    # 配置cassandra集群的ip
    contact_points=['ip1','ip2']
    # 配置登陆集群的账号和密码
    auth_provider=PlainTextAuthProvider(username='',password='')
    # 创建一个cassandra的cluster
    cluster=Cluster(contact_points=contact_points,auth_provider=auth_provider)
    # 连接并创建一个会话
    session=cluster.connect()
    # 定义一条cql查询语句
    simple_statement=SimpleStatement(cql,consistency_level=ConsistencyLevel.One)
    # 执行cql语句
    excute_result=session.execute(simple_statement,timeout=None)
    # 获取执行结果
    result=excute_result._current_rows

 

标签:cur,Python,数据库,cursor,result,操作,self,conn
From: https://www.cnblogs.com/zongchen/p/18067247

相关文章

  • Python全栈开发武沛齐day07模块
    day07模块1.知识回顾• 模块的分类-自定义模块内置第三方模块• 自定义模块– 关于拆分crmutilsencrypt.pydb.pymessage.pyapp.py– 文件夹和文件(扩展)py文件->模块文件夹->包py2的包:内部必须有一个init.pypy3的包:无限制– 导入模块• 去哪里......
  • Python全栈开发武沛齐day06模块
    day06模块今日概要:环境搭建、基础语法、数据类型、函数->基本操作模块,别人帮我们写好的一大堆的功能代码。模块:-自定义模块-功能简单,一个py文件就能实现功能。-功能多or负责,一个py文件的功能拆分到多个py文件-内置模块,Python内部已经携带。 importos impo......
  • MySQL数据库表关系详解
    MySQL数据库表关系详解(1)一对一一对一关系是最好理解的一种关系,在数据库建表的时候可以将人表的主键放置与身份证表里面,也可以将身份证表的主键放置于人表里面一对一的关系就是一种特殊的多对多的关系,一张表A中的一条记录只能对应另一张表B中的一条记录,另一张表B中的一条记......
  • 实现Python pdf切割 ValueError: seek of closed file
    参考网上的教材,实现pdf文件的切割,提示一个问题ValueError:seekofclosedfile原来是pdf文件关闭导致的问题。将其改成一个程序就解决了。importPyPDF2pdf_path=r'E:\zhuanxie\jpm\2.pdf'out_path=r'E:\zhuanxie\jpm\23.pdf'#切割PDF文件start_page=1end_page=......
  • flowable的查询操作和删除操作
    效果图 pom文件<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http......
  • python打印三角形图案
    格式如图: 代码实现:deftriangle(row):foriinrange(1,row+1):forxinrange(i):print('*',end='')print()foriinrange(1,row+1):forxinrange(row-i):print('',end=&#......
  • python3实现xmind用例转excel
    1importxmindparser2importxlwt,xlrd3fromxlutils.copyimportcopy4fromxlwtimportWorksheet5fromxmindparserimportxmind_to_dict6importdatetime7importos8importre9importtraceback1011#当前时间戳12a=datetim......
  • 7-3 jmu-python-统计字符个数
    输入一个字符串,统计其中数字字符及小写字符的个数输入格式:输入一行字符串输出格式:共有?个数字,?个小写字符,?填入对应数量输入样例:helo134ss12输出样例:共有5个数字,6个小写字符代码长度限制16KB时间限制400ms内存限制64MB#读取一行字......
  • Python 中的推导式
    python中主要在列表、字典和集合中使用推导式。推导式就是对数据集(无论是列表、字典还是集合)的操作,一般只需要几行代码,可以将其收缩到一行或多行,从而提高可读性并使代码紧凑。 常见的推导式有:·列表推导式·字典推导式·集合推导式·生成器推导式列表推导式列表推导式一......
  • Python 初学者容易踩的 5 个坑
    哈喽大家好,我是咸鱼。今天咸鱼列出了一些大家在初学Python的时候容易踩的一些坑,看看你有没有中招过。原文:https://www.bitecode.dev/p/unexpected-python-traps-for-beginners不明显的字符串拼接Python在词法分析的时候会把多个字符串自动拼接起来。data="very""lazy"p......