python写vim script 之 山寨版 dbext

山寨版 dbext
需要有python支持的vim,windows版的gvim已经有python支持
需要安装python2.4(其他版本好像不行)
pymssql,cx_oracle.


"==================================================
" File: SzDbext.vim
" Brief: 山寨版dbext
" Authors: shrek<shrek.wang AT gmail DOT com>
" Last Change: 2009-01-20 22:33:06
" Version: 0.00000000000000000000000000000002
" Licence: LGPL
"
"
" Usage: 1:修改SzDbext.vim中的数据库连接参数
" 2:放到 plugin 目录下
" 3:编辑任竟文件
" 4:用v命令选中文本块
" 4: ,, 查询选定的sql
" ,dt 查询选定文本的表结构
" ,lt 列出包含选定文本的表
"
" Todo: 1:将数据库的连接参数用vim变量独立出来
" 2:支持ddl


let g:selection=-1
python profile={}

function! GetDbOption()
python << EOF
from vim import *

aa=dict(host="192.168.0.280",user="**",password="**",database="data1")
bb=dict(host="192.168.0.281",user="**",password="**",database="sat2")
cc=dict(host="192.168.0.282",user="**",password="**",database="data3")

array=[aa,bb,cc]
selection=eval("g:selection")
if int(selection) < 0 :
for index,item in enumerate(array):
print str(index) + ": "+item["host"]+": "+item["database"]
command("let g:selection=input('please enter a selection')")
selection=eval("g:selection")
profile=array[int(selection)]
print profile


EOF
endfunction


function! GetVisualBlock() range
let save = @"
silent normal gvy
let vis_cmd = @"
let @" = save
return vis_cmd
endfunction

function! SwitchToSQLResult()
let s:cur_buf = bufnr("%")
let s:szdb_result_buf=bufnr("SzdbResult")
if bufwinnr(s:szdb_result_buf) > 0
exec bufwinnr(s:szdb_result_buf) . "wincmd w"
%d
else
exec 'silent! botright split SzdbResult'
exec "e SzdbResult"
exec "set nowrap"
endif

endfunction

function! QueryVisualSQL() range
python << EOF
import vim
vb=vim.eval("GetVisualBlock()")
lines=vb.split("\n")
sql=""
for line in lines:
sql=sql+line+" "
vim.command('call QuerySQL("'+sql+'")')
EOF
endfunction

function! QuerySQL(sql)
python << EOF
import vim
if not profile:
vim.command("call GetDbOption()")

conn=""
if profile.has_key("sid") :
import cx_Oracle
dns_tns=cx_Oracle.makedsn(profile["host"],1521,profile["sid"])
conn = cx_Oracle.connect(profile["user"], profile["password"], dns_tns)
else :
import pymssql
conn = pymssql.connect(host=profile["host"],user=profile["user"], \
password=profile["password"],database=profile["database"])


cur = conn.cursor()

sql=vim.eval("a:sql")
cur.execute(sql)

columns,maxlens=[],[]
vim.command("call SwitchToSQLResult()")
if cur.description:
for column in cur.description:
columns.append(column[0])
maxlens.append(0)

resultset=[columns]
for row in cur.fetchall():
for index,field in enumerate(row):
if (len(str(field))>maxlens[index]):
maxlens[index]=len(str(field))
resultset.append(row)

for index,field in enumerate(columns):
if (len(str(field))>maxlens[index]):
maxlens[index]=len(str(field))

headline=""
for item in maxlens:
headline=headline+"+"+("-"*item)+"--"
headline=headline+"+"

for rowindex,row in enumerate(resultset):
line=""
for index,field in enumerate(row):
line=line+"| "+str(field).replace("\n","").ljust(maxlens[index]+1)
if rowindex<2: vim.current.buffer.append(headline)
vim.current.buffer.append( line+"|")
vim.current.buffer.append( headline)
vim.current.buffer[0]="Host:"+profile["host"]+" Database:"+profile["database"]
vim.current.buffer.append("affected "+str(cur.rowcount)+" rows.")
conn.commit()
cur.close()
conn.close()
EOF
redraw!
exec bufwinnr(s:cur_buf) . "wincmd w"
endfunction

function! QueryTables()
python << EOF
import vim
vb=vim.eval("GetVisualBlock()")
if profile.has_key("sid"):
sql="select table_name from user_tables where table_name like '%"+vb.upper()+"%'"
else:
sql="SELECT name FROM sysobjects Where name like '%"+vb+"%' and type = 'U' order by name"
vim.command('call QuerySQL("'+sql+'")')
EOF
endfunction

function! DescTable()
python << EOF
import vim
vb=vim.eval("GetVisualBlock()")

if profile.has_key("sid"):
sql="select column_name,data_type from user_tab_columns where table_name = '"+vb.upper()+"'"
else:
sql="""Select col.[name] as '字段名', type.[name] as '类型' , col.[length]as '长度' \
From syscolumns as col \
Left Join systypes as type on col.xtype = type.xtype \
where col.id = (Select id From sysobjects Where name = '"""+vb+"')"

vim.command('call QuerySQL("'+sql+'")')
EOF
endfunction

map <silent>,, :call QueryVisualSQL()<cr>
map <silent>,dt :call DescTable()<cr>
map <silent>,lt :call QueryTables()<cr>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
vim的数据库连接插件,便于数据库SQL调试,支持几乎所有的常见数据库, For instructions on installing this file, type :help add-local-help |add-local-help| inside Vim. Homepage: http://vim.sourceforge.net/script.php?script_id=356 SourceForge: $Revision: 1.23 $ *dbext* *dbext.vim* *db_ext* *db_ext.vim* *database-extension* *pgsql* *mysql* *asa* *ase* *ingres* *interbase* *sqlite* *sqlsrv* *ora* *db2* 1. Overview |dbext-overview| 2. Installation |dbext-install| 3. Configuration |dbext-configure| 3.1 Displaying Results |dbext-configure-results| 3.2 Script Variables |dbext-configure-variables| 3.3 Database Specific Options |dbext-configure-options| 3.4 DB2 Modes |dbext-configure-db2| 4. Mappings and commands |dbext-mappings| 5. Adding new database types |dbext-newdb| 6. Prompting for input parameters |dbext-prompting| 7. Setting up connection information |dbext-connect| 7.1 Connection Parameters |dbext-connect-parameters| 7.2 Prompting for Parameters |dbext-connect-prompting| 7.3 Connection profiles |dbext-connect-profiles| 7.4 Connection information in modelines |dbext-connect-modelines| 7.5 Asking for connection parameters |dbext-connect-ask| 8. Creating mappings using dbext commands |dbext-in-mappings| 9. Object Completion |dbext-completion| 10. Listing Objects in the Database |dbext-list-objects| 11. Plugin integration |dbext-integration| 11.1 OMNI completion integration |dbext-omni-completion| 11.2 Intellisense integration |dbext-intellisense| 12. Filetype support |dbext-filetypes| 12.1 Using filetype support |dbext-filetypes-using| 12.2 Adding new filetypes |dbext-filetypes-adding| 13. Using SQL History |dbext-history| 14. Open Source |dbext-sourceforge| 15. Tutorial |dbext-tutorial| {Vi does not have any of this} ------------------------------------------------------------------------------ What's New *dbext-new* Version 4.20 New Features ------------ - Improved support for Cygwin. If you are using a Cygwin compiled Vim (on Windows) and are accessing Windows compiled binaries (i.e. sqlplus.exe) the binary will complain since it does not understand Unix path names. Added the option g:dbext_default_use_win32_filenames which allows you to indicate the binaries must use translated Windows paths instead. (Richard) - DBGetOption displays more information. Bug Fixes ------------ - SQL Server support had issues with the queries when running DBCompleteTable, DBCompleteProcedure, DBCompleteView which also affected the sqlcomplete.vim plugin included with Vim7 (Albie Janse van Rensburg). Version 4.10 New Features ------------ - Updated DBGetOption to additionally display a list of all database profiles and their types. All dbext options that have been overriden via the vimrc are also displayed. Bug Fixes ------------ - db2 support had issues with the queries when running DBCompleteTable, DBCompleteProcedure, DBCompleteView which also affected the sqlcomplete.vim plugin included with Vim7 (Peter Princz). - The documentation was still indicating there was a plugin dependency which has been removed with Vim7. Version 4.00 New Features ------------ - dbext.vim now requires Vim7. - dbext.vim required 2 additional plugins multvals and genutil to operate. These dependencies have been removed by taking advantage of the new Vim7 features (Lists and Dictionaries). - When using the DBCompleteTable, DBCompleteProcedure, DBCompleteView commands errors are displayed instead of silently ignored. This makes them more useful with the sqlComplete plugin (see |sql.txt|). - Added new option, dbext_default_MYSQL_version, for MySQL to indicate the version you using. - You can optionally define a function, DBextPostResult, in your .vimrc, this function will be called each time the result window is updated. This function can be used to do anything, for example, syntax highlighting the result set in the result window.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值