环境:
python3.6 64bit
pycharm201664bit
Oracle 11 64bit
SQLServer 2019
Mysql
步骤1:在pycharm上安装相应的包,可通过pip或者其他方式
步骤2:import这些包
import pymysql,pymssql,cx_Oracle #导入数据库相关包
Oracle:
import cx_Oracle #导入包
#db = cx_Oracle.connect('用户名','用户密码','ip:端口号/数据库名') #连接数据库
db = cx_Oracle.connect('od','123456','127.0.0.1:1521/orcledb') #连接数据库
print(db.version) #打印版本看看 显示 11.2.0.1.0
cur = db.cursor() # 游标操作
cur.execute("SELECT * FROM TIMP ") # 执行sql语句
rows = cur.fetchall() # 获取数据
print(rows)
# 打印数据
for row in rows[:10]:
print(f"{row[0]} ,",end='')
Mysql :
# "host":"127.0.0.1","account":"root","passwd":"123456","port":3700,"db":"student"
conn = pymysql.connect(
host=data_db['host'],
user=data_db['account'],
passwd=data_db['passwd'],
port=data_db['port'],
db=data_db['db'],
charset='utf8',
cursorclass=pymysql.cursors.DictCursor)
cursor = conn.cursor()
sql_warning_value = "SELECT name,phone,tm FROM banji ;"
cursor.execute(sql_warning_value)
values_warning_words = cursor.fetchall()
# 关闭数据库连接
cursor.close()
conn.close()
也可以弄成配置文件形式 price.yaml
mysql:
config:
host: "127.0.0.1"
user: "root"
password: "123456"
port: 3306
db: "student"
parameters:
fileds:
url: "https://***.shtml"
访问并连接数据库
import sys
import yaml
import pymysql
r_path = sys.path[0]
yaml_file = r_path + "/config/price.yaml"
with open(yaml_file, encoding='utf-8') as f:
cfg = yaml.safe_load(f)
data_db = cfg['mysql']['config']
title_url = cfg['parameters']['fileds']['url']
conn = pymysql.connect(
host=data_db['host'],
user=data_db['user'],
passwd=data_db['password'],
port=data_db['port'],
db=data_db['db'],
charset='utf8',
cursorclass=pymysql.cursors.DictCursor)
cursor = conn.cursor() # 游标操作
'''
访问数据库,库名一定要写正确,表明是区分大小写的。
'''
SQLServer:
conn= pymssql.connect(host='127.0.0.1',port=1433,user='sa',password='123456yu',database='water',charset = 'utf8')
#连接SQLServer
host后面接数据库服务器所在的ip地址,port是端口号,一般为默认值,user是访问者的用户名,password是访问者的密码,database是需要访问的某个数据库名称。
- 端口如果不写,默认为1433,如果当前的数据库实例不是使用1433的端口,就会报错;
- server='LAPTOP-N234S6AE',加不加都可以,如果加上,去除host也没事
网友评论