Last active
February 25, 2020 09:01
-
-
Save cosven/29a34ddc97151f14a0dc6104d9b3985d to your computer and use it in GitHub Desktop.
一个方便测试 sql 的脚本,配合 ipython notebook 使用味道更佳...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
这个脚本的好处:运行 sql 并能看到 sql 的输出,输出格式类似 mysql client。 | |
比如,运行下面这个脚本,会有如下输出。 | |
``` | |
i j | |
1 3 | |
(1062, "Duplicate entry '1' for key 'PRIMARY'") | |
i j | |
1 2 | |
``` | |
""" | |
import click | |
from mycli.main import MyCli | |
def create_session(host='127.0.0.1', port=3306): | |
mycli = MyCli() | |
mycli.connect(host=host, | |
port=port, | |
user='root', | |
passwd='', | |
database='test', | |
) | |
mycli.formatter.format_name = 'tsv' | |
return mycli | |
def run(mycli, sql): | |
try: | |
mycli.run_query(sql, new_line=True) | |
except Exception as e: | |
click.secho(str(e), err=True, fg='red') | |
mysql_conn_info = dict(host='127.0.0.1', port=3306) | |
session = create_session(**mysql_conn_info) | |
sql = ''' | |
-- set @@tidb_txn_mode = 'optimistic'; | |
use test; | |
drop table if exists t; | |
create table t(i int primary key, j int); | |
insert into t values (1, 2); | |
begin; | |
insert into t values (1, 3); | |
select * from t; | |
delete from t where j = 3; | |
commit; | |
select * from t; | |
''' | |
run(session, sql) | |
run(session, 'select * from t;') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
配合 ipython notebook 效果图