内容
サクラエディタからDB接続をしたい。
基本的には現場で推奨されているエディタ・開発環境を使うのだが
重くてストレスがたまることがある。
自由にソフトウェアをインストールすることも
できないので、簡単に作ってみようということ(ただの暇つぶしだったり)
方法
サクラエディタにはマクロ機能があり
vbs,jsを使用することができるので
vbsでDB接続する
■以下コード
max = GetLineCount(0)
' 0 否選択 1 選択中 2 矩形選択
selectFlg = IsTextSelected()
' 未選択の場合、
if selectFlg = 0 then
strSql = ""
for i = 1 to max
strSql = strSql & getLineStr(i)
if instr(strSql, ";") > 0 then
dbConnect(strSql)
strSql = ""
end if
next
' 選択中の文字列からSQLを取り出す
else
strSql = GetSelectedString()
strSql = split(strSql, ";")
for i = 0 to Ubound(strSql) -1
GoFileEnd
Down
insText(vbcr)
dbConnect(strSql(i))
next
end if
msgbox "finish", vbInfomation
'-----------------------------------------
' DB接続
'-----------------------------------------
sub dbConnect(strSql)
' ここではODBCに登録しているものを使用
strConn = "DSN=test"
Set oConn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
oConn.ConnectionString = strConn
oConn.Open
rs.Open strSql, oConn
' 検索の場合、エディタに出力
if instr(strSql, "select") > 0 or instr(strSql, "SELECT") > 0 then
outputCol = ""
colCount = rs.Fields.Count
for j = 0 to colCount -1
outputCol = outputCol & rs.Fields(j).Name & vbtab
next
insText(outputCol & vbcr)
do while rs.EOF <> True
output = ""
for j = 0 to colCount -1
output = output & rs.Fields(j).Value & vbtab
next
insText(output & vbcr)
rs.moveNext
loop
end if
' 解放
rs.Close
set rs = Nothing
oConn.Close
set oConn = Nothing
End sub
■作成後
サクラエディタでSQlを編集してすぐに実行したいときは
使う機会もあるけどやっぱり無理がある
■コマンドライン経由で
「外部コマンドを実行」というコマンドがあるので
サクラエディタからコマンドラインで実行してみる。
DBはmysql
connect = "mysql -u[userName] -p[password] -D[test] -e "
max = GetLineCount(0)
' 0 否選択 1 選択中 2 矩形選択
selectFlg = IsTextSelected()
' 未選択の場合、
if selectFlg = 0 then
strSql = ""
for i = 1 to max
strSql = strSql & getLineStr(i)
if instr(strSql, ";") > 0 then
' コマンド作成
exeStr = connect & """" & strSql & """"
' コマンド実行
ExecCommand exeStr, 1
strSql = ""
end if
next
' 選択中の文字列からSQLを取り出す
else
strSql = GetSelectedString()
strSql = split(strSql, ";")
for i = 0 to Ubound(strSql) -1
GoFileEnd
Down
insText(vbcr)
dbConnect(strSql(i))
next
end if
msgbox "finish", vbInfomation
以下のコマンド・SQLを実行してみる
show global variables like '%wait%';
select * from historycal where code = '3900' and date = current_date() -5;