0001-临时

select r2.table_catalog as owner,r2.table_name,r2.column_name,r2.data_type,coalesce(r2.character_maximum_length,r2.numeric_precision,null) as data_length,r1.description as comments from 
(
SELECT
	DISTINCT
	A.attrelid,
	c.relname,
	a.attname,
	a.attnum,
	d.description
FROM
	pg_class C,
	pg_attribute A,
	pg_description d
WHERE
	C .relname = 'user'
AND d.objoid = C .oid
AND d.objoid = A .attrelid
AND d.objsubid = A .attnum
) r1,
(
select table_catalog,table_name,column_name,data_type,character_maximum_length,numeric_precision from information_schema.columns where table_name = 'user'
) r2
where (r1.relname,attname) = (r2.table_name,r2.column_name)



show grants for 'root'@'localhost';  

select user,host from mysql.user;




select CONCAT(user,'@',host) as jurl from mysql.user

show grants for (select CONCAT(user,'@',host) as jurl from mysql.user);

create user 'boss'@'localhost' IDENTIFIED by '123456';	-- boss 用户拥有查看所有数据库所有表的权限
grant select on *.* to boss@localhost;

create user 'leader'@'localhost' IDENTIFIED by '123456';	-- leader 用户拥有查看某个数据库所有表的权限
grant select on mysqldb.* to leader@localhost;

create user 'employee'@'localhost' IDENTIFIED by '123456';	-- boss 用户拥有查看具体某个表的权限
grant select on mysqldb.students to employee@localhost;


-- 1)如果根据 user 和 host 查询 mysql.user 的 Select_priv的值为 Y,则查出所有数据库的所有表 select TABLE_SCHEMA,TABLE_NAME from information_schema.TABLES
-- 2)如果上述 Select_priv的值为 N,则根据 db 和 user、host 查询 mysql.db 的 Select_priv的值,如果为 Y,则查询出指定 db 下所有的表 select TABLE_SCHEMA,TABLE_NAME from information_schema.TABLES where TABLE_SCHEMA = 'mysqldb'
-- 3)如果上述 Select_priv的值为 N,则根据 db、user、host、host 查询 mysql.table_priv 查出所有表 select t.Table_priv from tables_priv t where (t.db,user,t.host) = ('mysqldb','employee','localhost');



if EXISTS(select u.Select_priv from mysql.user u where (u.host,u.User,u.Select_priv) = ('localhost','boss','Y')) THEN
		select TABLE_SCHEMA,TABLE_NAME from information_schema.TABLES
	ELSEIF EXISTS(select d.Select_priv from mysql.db d where (d.db,d.host,d.User,d.Select_priv) = ('mysqldb','localhost','boss','Y')) THEN
		select TABLE_SCHEMA,TABLE_NAME from information_schema.TABLES where TABLE_SCHEMA = 'mysqldb'
	ELSEIF EXISTS(select t.table_name from mysql.table_priv t where (t.db,t.host,t.User) = ('mysqldb','localhost','boss')) THEN
		select t.table_name from mysql.tables_priv t where (t.db,t.host,t.User) = ('mysqldb','localhost','boss')
	ELSE
		''
	END if



select COLUMN_TYPE, substring(COLUMN_TYPE,INSTR(COLUMN_TYPE,'(')+1,INSTR(COLUMN_TYPE,')')-INSTR(COLUMN_TYPE,'(')-1)  from information_schema.columns where table_name='students';



select TABLE_SCHEMA as owner,TABLE_NAME,column_name,data_type,substring(COLUMN_TYPE,INSTR(COLUMN_TYPE,'(')+1,INSTR(COLUMN_TYPE,')')-INSTR(COLUMN_TYPE,'(')-1) as data_length,column_comment from information_schema.columns where table_name='students';



SELECT
	TABLE_SCHEMA AS OWNER,
	TABLE_NAME,
	column_name,
	data_type,
	if(data_type in('char','int','smallint','tinyint','mediumint','integer','bigint','double','float'),
		substring(
			COLUMN_TYPE,
			INSTR(COLUMN_TYPE, '(') + 1,
			INSTR(COLUMN_TYPE, ')') - INSTR(COLUMN_TYPE, '(') - 1
		),'') AS data_length,

	column_comment,COLUMN_TYPE
	
FROM
	information_schema. COLUMNS
WHERE
	table_name = 'tt';



LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': '[%(levelname)s][%(asctime)s][%(filename)s][%(funcName)s][%(lineno)d]> %(message)s'
        },
        'simple': {
            'format': '[%(levelname)s]> %(message)s'
        },
    },
    'filters': {
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },  # print any DEBUG (or higher) message
        'file_handler': {
            'level': 'INFO',
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': '{}/{}'.format(BASE_DIR,'padp_cloud.log'),
            'encoding': 'utf-8',
            'formatter': 'standard'
        },  # 用于文件输出
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
            'formatter': 'standard'
        },  # 会向站点管理员发送日志,可以在后台使用 admin 查看 log
    },
    'loggers': {
        'django': {
            'handlers': ['console', 'file_handler'],
            'level': 'DEBUG',
            'propagate': True,
        },
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': False,
        },
    }
}

协程

1)python3.4	asynico + yield form
	异步操作,需要在coroutine中通过yield from完成。
	
	'''
	coroutine:协程
	@asyncio.coroutine把一个 generator标记为 coroutine类型
	yield from语法可以让我们方便地调用另一个generator

	协程就是单个线程,它可以在程序内部中断,然后进入另外一个子程序,在适当的时候又回到原来的程序继续执行。
	因为协程没有锁机制,也不需要来回切换线程,所以协程执行效率非常高。
	'''
	
	import asyncio

	# IO 操作函数
	@asyncio.coroutine
	def readFile(i):
		k = 0
		with open('img.txt',mode='r',encoding='utf8') as f:
			for line in f:
				k += 1
		print('over----------k={}'.format(k+i))

	# 包含耗时的 IO 操作的函数
	@asyncio.coroutine
	def one(i):
		print('-------模拟进行 IO 操作-----------开始:{}'.format(i))
		yield from asyncio.gather(readFile(i))
		print('-------模拟进行 IO 操作-----------结束:{}'.format(i))
		return 100 + i  # 不指定 return,则返回 None

	@asyncio.coroutine
	def test(i):  # 在函数前加 async,将函数变成一个协程
		print("test_1", i)
		# r = await asyncio.sleep(2)    # asyncio.sleep(secodes):模拟 IO 操作
		r = yield from one(i)                 # one(i):一个耗时的 IO 操作
		print(r)
		print("test_2", i,'\n')

	loop = asyncio.get_event_loop()         # get_event_loop():返回一个异步的循环事件
	tasks = [test(i) for i in range(5)]     # 任务列表
	loop.run_until_complete(asyncio.wait(tasks))
	loop.close()
	
	输出结果:
	test_1 3
	-------模拟进行 IO 操作-----------开始:3
	test_1 4
	-------模拟进行 IO 操作-----------开始:4
	test_1 0
	-------模拟进行 IO 操作-----------开始:0
	test_1 2
	-------模拟进行 IO 操作-----------开始:2
	test_1 1
	-------模拟进行 IO 操作-----------开始:1
		<输出到这里时会停顿一会儿,因为这时在读取文件内容>
	over----------k=1001003
		<输出到这里时会停顿一会儿,因为这时在读取文件内容>
	over----------k=1001004
		<输出到这里时会停顿一会儿,因为这时在读取文件内容>
	over----------k=1001000
		<输出到这里时会停顿一会儿,因为这时在读取文件内容>
	over----------k=1001002
		<输出到这里时会停顿一会儿,因为这时在读取文件内容>
	over----------k=1001001
	-------模拟进行 IO 操作-----------结束:3
	103
	test_2 3 

	-------模拟进行 IO 操作-----------结束:4
	104
	test_2 4 

	-------模拟进行 IO 操作-----------结束:0
	100
	test_2 0 

	-------模拟进行 IO 操作-----------结束:2
	102
	test_2 2 

	-------模拟进行 IO 操作-----------结束:1
	101
	test_2 1 
	
	
2)python3.5	asynico + await
	异步操作,需要在coroutine中通过yield from完成。
	
	import asyncio

	# IO 操作函数
	async def readFile(i):
		k = 0
		with open('img.txt',mode='r',encoding='utf8') as f:
			for line in f:
				k += 1
		print('over----------k={}'.format(k+i))

	# 包含耗时的 IO 操作的函数
	async def one(i):
		print('-------模拟进行 IO 操作-----------开始:{}'.format(i))
		await asyncio.gather(readFile(i))
		print('-------模拟进行 IO 操作-----------结束:{}'.format(i))
		return 100 + i  # 不指定 return,则返回 None

	async def test(i):  # 在函数前加 async,将函数变成一个协程
		print("test_1", i)
		# r = await asyncio.sleep(2)    # asyncio.sleep(secodes):模拟 IO 操作
		r = await one(i)                 # one(i):一个耗时的 IO 操作
		print(r)
		print("test_2", i,'\n')

	loop = asyncio.get_event_loop()         # get_event_loop():返回一个异步的循环事件
	tasks = [test(i) for i in range(5)]     # 任务列表
	loop.run_until_complete(asyncio.wait(tasks))
	loop.close()
	
	执行结果:
	test_1 3
	-------模拟进行 IO 操作-----------开始:3
	test_1 4
	-------模拟进行 IO 操作-----------开始:4
	test_1 0
	-------模拟进行 IO 操作-----------开始:0
	test_1 2
	-------模拟进行 IO 操作-----------开始:2
	test_1 1
	-------模拟进行 IO 操作-----------开始:1
		<输出到这里时会停顿一会儿,因为这时在读取文件内容>
	over----------k=1001003
		<输出到这里时会停顿一会儿,因为这时在读取文件内容>
	over----------k=1001004
		<输出到这里时会停顿一会儿,因为这时在读取文件内容>
	over----------k=1001000
		<输出到这里时会停顿一会儿,因为这时在读取文件内容>
	over----------k=1001002
		<输出到这里时会停顿一会儿,因为这时在读取文件内容>
	over----------k=1001001
	-------模拟进行 IO 操作-----------结束:3
	103
	test_2 3 

	-------模拟进行 IO 操作-----------结束:4
	104
	test_2 4 

	-------模拟进行 IO 操作-----------结束:0
	100
	test_2 0 

	-------模拟进行 IO 操作-----------结束:2
	102
	test_2 2 

	-------模拟进行 IO 操作-----------结束:1
	101
	test_2 1 
	
说明:python3.4与python3.5协程实现相比,只是把yield from换成了await,@asyncio.coroutine换成了async,其余不变。


Python通过yield提供了对协程的基本支持,但是不完全。而第三方的gevent为Python提供了比较完善的协程支持。
实际代码里,我们不会用gevent.sleep()去切换协程,而是在执行到IO操作时,gevent自动切换
1)单个类协程
from gevent import monkey; monkey.patch_socket()
import gevent

def f(n):
	for i in range(n):
		print(gevent.getcurrent(), i)

g1 = gevent.spawn(f, 3)
g2 = gevent.spawn(f, 2)
g3 = gevent.spawn(f, 4)
g1.join()
g2.join()
g3.join()

执行结果:
<Greenlet "Greenlet-0" at 0x352f948: f(3)> 0
<Greenlet "Greenlet-0" at 0x352f948: f(3)> 1
<Greenlet "Greenlet-0" at 0x352f948: f(3)> 2
<Greenlet "Greenlet-1" at 0x352fa48: f(2)> 0
<Greenlet "Greenlet-1" at 0x352fa48: f(2)> 1
<Greenlet "Greenlet-2" at 0x352fb48: f(4)> 0
<Greenlet "Greenlet-2" at 0x352fb48: f(4)> 1
<Greenlet "Greenlet-2" at 0x352fb48: f(4)> 2
<Greenlet "Greenlet-2" at 0x352fb48: f(4)> 3


2)多个协程
from gevent import monkey;monkey.patch_all()
import gevent
from urllib import request

def f(url):
	print('GET: %s' % url)
	resp = request.urlopen(url)
	data = resp.read()
	print('%d bytes received from %s.' % (len(data), url))

gevent.joinall([
	gevent.spawn(f, 'https://www.python.org/'),
	gevent.spawn(f, 'https://www.yahoo.com/'),
	gevent.spawn(f, 'https://github.com/'),
])

执行结果:
GET: https://www.python.org/
GET: https://www.yahoo.com/
GET: https://github.com/
59455 bytes received from https://github.com/.
48805 bytes received from https://www.python.org/.
519342 bytes received from https://www.yahoo.com/.


3)线程池
import gevent
from gevent import monkey, pool
monkey.patch_all()
from urllib import request

urls = [
	'http://fanyi.baidu.com/',
	'https://www.yahoo.com/',
	'https://baidu.com/',
]
p = pool.Pool(10)
jobs = []

def f(url):
	print('GET: %s' % url)
	resp = request.urlopen(url)
	data = resp.read()
	print('%d bytes received from %s.' % (len(data), url))

def test(f):
	jobs = []
	for url in urls:
		jobs.append(gevent.spawn(f, url))
	return jobs

pool.joinall(test(f))

执行结果:
GET: http://fanyi.baidu.com/
GET: https://www.yahoo.com/
GET: https://baidu.com/
117909 bytes received from https://baidu.com/.
179422 bytes received from http://fanyi.baidu.com/.
533397 bytes received from https://www.yahoo.com/.
SET @ROW_NUMBER:=0; 
SET @median_group:='';

SELECT 
    median_group, AVG(height) AS median
FROM
    (SELECT 
        @ROW_NUMBER:=CASE
                WHEN @median_group = gender THEN @ROW_NUMBER + 1
                ELSE 1
            END AS count_of_group,
            @median_group:=gender AS median_group,
            gender,
            height,
            (SELECT 
                    COUNT(*)
                FROM
                    heights
                WHERE
                    a.gender = gender) AS total_of_group
    FROM
        (SELECT 
        gender, height
    FROM
        heights
    ORDER BY gender , height) AS a) AS b
WHERE
    count_of_group BETWEEN total_of_group / 2.0 AND total_of_group / 2.0 + 1
GROUP BY median_group
select AVG(DISTINCT income)
from (
select T1.income from graduates T1,graduates T2
group by T1.income
having sum(case when T2.income >= T1.income then 1 else 0 end) >= count(*)/2
and sum(case when T2.income <= T1.income then 1 else 0 end) >= count(*)/2
) tmp;

CREATE FUNCTION dbo.RegexReplace  
(  
    @string VARCHAR(MAX),   --被替换的字符串  
    @pattern VARCHAR(255),  --替换模板  
    @replacestr VARCHAR(255),   --替换后的字符串  
    @IgnoreCase INT = 0 --0区分大小写 1不区分大小写  
)  
RETURNS VARCHAR(8000)  
AS   
BEGIN  
    DECLARE @objRegex INT, @retstr VARCHAR(8000)  
    --创建对象  
    EXEC sp_OACreate 'VBScript.RegExp', @objRegex OUT  
    --设置属性  
    EXEC sp_OASetProperty @objRegex, 'Pattern', @pattern  
    EXEC sp_OASetProperty @objRegex, 'IgnoreCase', @IgnoreCase  
    EXEC sp_OASetProperty @objRegex, 'Global', 1  
    --执行  
    EXEC sp_OAMethod @objRegex, 'Replace', @retstr OUT, @string, @replacestr  
    --释放  
    EXECUTE sp_OADestroy @objRegex  
    RETURN @retstr  
END  
GO  
--保证正常运行的话,需要将Ole Automation Procedures选项置为1    
EXEC sp_configure 'show advanced options', 1    
RECONFIGURE WITH OVERRIDE   
EXEC sp_configure 'Ole Automation Procedures', 1    
RECONFIGURE WITH OVERRIDE

猜你喜欢

转载自blog.csdn.net/weixin_42725107/article/details/82019573