1、运行环境:PyCharm Community Edition 2022.2.3、Python3.10、Window10操作系统
2、引入各种数据库模块安装命令:
开始--运行--cmd--输入下面对应命令后回车
- 引入操作Oracle数据库模块安装命令:pip install cx_Oracle
- 引入操作SQLServer数据库模块安装命令:pip install pymssql
- 引入操作MySQL数据库模块安装命令:pip install PyMySQL
- SQLite数据模块不需要安装,系统自带。
3、PyCharm软件里面敲代码进行测试
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
import pymysql #导入连接MySql数据库模块
#连接数据库
con=pymysql.connect(host='127.0.0.1',user='root',password='123456',charset='utf8')
#创建一个游标对象(相当于指针)
cursor=con.cursor()
#执行创建数据库语句
cursor.execute('show databases;')
#fetchone获取一条数据(元组类型)
print(cursor.fetchone())
#关闭游标和数据库连接
cursor.close()
con.close()
import cx_Oracle as cx #导入连接Oracle数据库模块
con = cx.connect('***', '***', '192.168.31.204:1521/ORCL') #创建连接
cursor = con.cursor() #创建游标
cursor.execute("select * from TB_UD_USER where UserName='张三'") #执行sql语句
data = cursor.fetchone() #获取一条数据
print(data) #打印数据
cursor.close() #关闭游标
con.close() #关闭数据库连接l
import pymssql #导入连接SqlServer数据库模块
#创建连接对象
con = pymssql.connect(server='.',user='sa',password='***',database='***') #服务器名,账户,密码,数据库名
cursor = con.cursor() #创建游标
cursor.execute("select * from dbo.UserTable where UserName='张三'") #执行sql语句
data = cursor.fetchone() #获取一条数据
print(data) #打印数据
cursor.close() #关闭游标
con.close() #关闭数据库连接
import sqlite3 #导入连接SQLite数据库模块
#创建连接对象
con = sqlite3.connect("D:/testFile/testdata.db") #本地sqlite数据库文件绝对路径
cursor = con.cursor() #创建游标
cursor.execute("select * from TB_UD_USER where UserName='张三'") #执行sql语句
data = cursor.fetchone() #获取一条数据
print(data) #打印数据
cursor.close() #关闭游标
con.close() #关闭数据库连接
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('PyCharm')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/