python读取本地db文件(python 读取本地文件)
python怎么打开数据库文件
以打开mysql数据库为例来说明:
#!/usr/bin/python
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
#打开游标
cursor = db.cursor()
# 执行数据库查询
cursor.execute("SELECT VERSION()")
# 获取结果集的第一行
data = cursor.fetchone()
print "Database version : %s " % data
# 关闭连接
db.close()
python 怎样通过遍历以下文件后全部读到mongodb数据库中?
python 访问 mongodb 需要先安装 pymongo,如下:
1
pip?install?pymongo
txt 文件格式:
代码如下:
#coding=utf-8?from?pymongo?import?MongoClient?conn?=?MongoClient('127.0.0.1',?27017)?#?连接?test?数据库,没有则自动创建db?=?conn.test???#?使用?students?集合,没有则自动创建students?=?db.students?#?打开学生信息文件,?并将数据存入到数据库with?open('students.txt',?'r')?as?f:?????????for?line?in?f.readlines():?????????????????#?分割学生信息????????items?=?line.strip('\r').strip('\n').split(',')?????????????????#?添加到数据库????????students.insert({?'stu_id':?items[0],?'name':?items[1],?'grade':?int(items[2])?})?#?数据库查询学生信息并打印出来for?s?in?students.find():????print(s)
python 操作DB
//兼容2、3,使用Mysql,sqlite,gadfly
//py2版本
import os
from random import randrange as rand
COLSIZ = 10
FIELDS = ('login', 'userid', 'projid')
RDBMSs = {'s': 'sqlite', 'm': 'mysql', 'g': 'gadfly'}
DBNAME = 'test'
DBUSER = 'root'
DB_EXC = None
NAMELEN = 16
tformat = lambda s: str(s).title().ljust(COLSIZ)
cformat = lambda s: s.upper().ljust(COLSIZ)
def setup():
return RDBMSs[raw_input('''
Choose a database system:
(M)ySQL
(G)adfly
(S)QLite
Enter choice: ''').strip().lower()[0]]
def connect(db):
global DB_EXC
dbDir = '%s_%s' % (db, DBNAME)
if db == 'sqlite':
try:
import sqlite3
except ImportError:
try:
from pysqlite2 import dbapi2 as sqlite3
except ImportError:
return None
DB_EXC = sqlite3
if not os.path.isdir(dbDir):
os.mkdir(dbDir)
cxn = sqlite3.connect(os.path.join(dbDir, DBNAME))
elif db == 'mysql':
try:
import MySQLdb
import _mysql_exceptions as DB_EXC
except ImportError:
return None
try:
cxn = MySQLdb.connect(db=DBNAME)
except DB_EXC.OperationalError:
try:
cxn = MySQLdb.connect(user=DBUSER)
cxn.query('CREATE DATABASE %s' % DBNAME)
cxn.commit()
cxn.close()
cxn = MySQLdb.connect(db=DBNAME)
except DB_EXC.OperationalError:
return None
elif db == 'gadfly':
try:
from gadfly import gadfly
DB_EXC = gadfly
except ImportError:
return None
try:
cxn = gadfly(DBNAME, dbDir)
except IOError:
cxn = gadfly()
if not os.path.isdir(dbDir):
os.mkdir(dbDir)
cxn.startup(DBNAME, dbDir)
else:
return None
return cxn
def create(cur):
try:
cur.execute('''
CREATE TABLE users (
login VARCHAR(%d),
userid INTEGER,
projid INTEGER)
''' % NAMELEN)
except DB_EXC.OperationalError:
drop(cur)
create(cur)
drop = lambda cur: cur.execute('DROP TABLE users')
NAMES = (
('aaron', 8312), ('angela', 7603), ('dave', 7306),
('davina',7902), ('elliot', 7911), ('ernie', 7410),
('jess', 7912), ('jim', 7512), ('larry', 7311),
('leslie', 7808), ('melissa', 8602), ('pat', 7711),
('serena', 7003), ('stan', 7607), ('faye', 6812),
('amy', 7209), ('mona', 7404), ('jennifer', 7608),
)
def randName():
pick = set(NAMES)
while pick:
yield pick.pop()
def insert(cur, db):
if db == 'sqlite':
cur.executemany("INSERT INTO users VALUES(?, ?, ?)",
[(who, uid, rand(1,5)) for who, uid in randName()])
elif db == 'gadfly':
for who, uid in randName():
cur.execute("INSERT INTO users VALUES(?, ?, ?)",
(who, uid, rand(1,5)))
elif db == 'mysql':
cur.executemany("INSERT INTO users VALUES(%s, %s, %s)",
[(who, uid, rand(1,5)) for who, uid in randName()])
getRC = lambda cur: cur.rowcount if hasattr(cur, 'rowcount') else -1
def update(cur):
fr = rand(1,5)
to = rand(1,5)
cur.execute("UPDATE users SET projid=%d WHERE projid=%d" % (to, fr))
return fr, to, getRC(cur)
def delete(cur):
rm = rand(1,5)
cur.execute('DELETE FROM users WHERE projid=%d' % rm)
return rm, getRC(cur)
def dbDump(cur):
cur.execute('SELECT * FROM users')
print '\n%s' % ''.join(map(cformat, FIELDS))
for data in cur.fetchall():
print ''.join(map(tformat, data))
def main():
db = setup()
print '*** Connect to %r database' % db
cxn = connect(db)
if not cxn:
print 'ERROR: %r not supported or unreachable, exiting' % db
return
cur = cxn.cursor()
print '\n*** Create users table (drop old one if appl.)'
create(cur)
print '\n*** Insert names into table'
insert(cur, db)
dbDump(cur)
print '\n*** Move users to a random group'
fr, to, num = update(cur)
print '\t(%d users moved) from (%d) to (%d)' % (num, fr, to)
dbDump(cur)
print '\n*** Randomly delete group'
rm, num = delete(cur)
print '\t(group #%d; %d users removed)' % (rm, num)
dbDump(cur)
print '\n*** Drop users table'
drop(cur)
print '\n*** Close cxns'
cur.close()
cxn.commit()
cxn.close()
if name == ' main ':
main()
从数据库里python获取数据存到本地数据库
python项目中从接口获取数据并存入本地数据库
首先用postman测试接口
根据请求方式将数据存入数据库中
首先用postman测试接口
通过url,选择相应的请求方式,头部,数据格式,点击send看能否获取数据
根据请求方式将数据存入数据库中
下面是post请求方式def get() URL = '' HEADERS = {'Content-Type': 'application/json'} JSON = {} response = request.post(URL,headers=HEADERS,json=JSON) #json.loads()用于将str类型的数据转成dict jsondata = json.load(response.txt) for i in jsondata: date1 = i[data] type1 = i[type] ... #拼接sql语句 sql="" conn=MySQLdb.connect(host="localhost",user="root",passwd="sa",db="mytable") cursor=conn.cursor() ursor.execute(sql)
Python如何从文件读取数据
1.1 读取整个文件
要读取文件,需要一个包含几行文本的文件(文件PI_DESC.txt与file_reader.py在同一目录下)
PI_DESC.txt
3.1415926535
8979323846
2643383279
5028841971
file_reader.py
with open("PI_DESC.txt") as file_object:
contents = file_object.read()
print(contents)
我们可以看出,读取文件时,并没有使用colse()方法,那么未妥善的关闭文件,会不会导致文件收到损坏呢?在这里是不会的,因为我们在open()方法前边引入了关键字with,该关键字的作用是:在不需要访问文件后将其关闭
1.2文件路径
程序在读取文本文件的时候,如果不给定路径,那么它会先在当前目录下进行检索,有时候我们需要读取其他文件夹中的路径,例如:
现在文件PI_DESC.txt存储在python目录的子文件夹txt中
那么我们读取文本内容的代码得修改为:
with open("txt\PI_DESC.txt") as file_object:
contents = file_object.read()
print(contents)
给open参数传递的参数得给相对路径
在Windows中,使用反斜杠(\),但是由于python中,反斜杠被视为转义字符,在Windows最好在路径开头的单(双)引号前加上r
相对路径:即相对于程序文件的路径
绝对路径:即文本在硬盘上存储的路径
使用绝对路径的程序怎么写呢 ?
with open(r"D:\python\txt\PI_DESC.txt") as file_object:
contents = file_object.read()
print(contents)
1.3逐行读取
读取文件时,可能需要读取文件中的每一行,要以每一行的方式来检查文件或者修改文件,那么可以对文件对象使用for循环
file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:
for line in file_object:
print(line)
程序运行结果如下:
通过运行结果我们可以看出,打印结果中间有很多空白行,这些空白行是怎么来的呢?因为在这个文件中,每行的末尾都有一个看不见的换行符,而print语句也会加一个换行符,因此每行末尾就有2个换行符:一个来自文件,另外一个来自print,消除这些换行符,只需要使用方法rstrip()
file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:
for line in file_object:
print(line.rstrip())
打印结果
通过运行结果我们可以看出,打印结果中间有很多空白行,这些空白行是怎么来的呢?因为在这个文件中,每行的末尾都有一个看不见的换行符,而print语句也会加一个换行符,因此每行末尾就有2个换行符:一个来自文件,另外一个来自print,消除这些换行符,只需要使用方法rstrip()
file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:
for line in file_object:
print(line.rstrip())
打印结果
1.4创建一个包含文件各行内容的列表
使用关键字with时,open()返回的文件对象只能在with代码块可用,如果要在with代码块外访问文件的内容,可在with块中将文件各行存储在一个列表,并在with代码块外使用该列表
file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:
lines = file_object.readlines()for line in lines:
print(line.rstrip())
1.5使用文件的内容
在上面一节中我们提到把数据提取到内存中,那么我们就可以对数据进行随心所欲的操作了
需要:将圆周率连在一起打印出来(删除空格),并打印其长度
file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:
lines = file_object.readlines()pi_str = ''for line in lines:
pi_str += line.strip()print(pi_str.rstrip())print(len(pi_str.rstrip()))
file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:
lines = file_object.readlines()pi_str = ''for line in lines:
pi_str += line.strip()print(pi_str.rstrip())print(len(pi_str.rstrip()))
注意最后print语句并没有缩进,如果是缩进的话就会每取一行打印一次
打印效果如下
python中导入db提示未引用?
from . import db
这种引入方式是指在你的py文件同级的目录下有一个db文件,这时你可这样进行导入。
如果你要引入的是第三方库的话,那就不是这样引入的,可以试试以下方式:
from 库名 import 方法名
或
import 库名