やってみる

アウトプットすべく己を導くためのブログ。その試行錯誤すらたれ流す。

SQLite3コア関数 printf

 C言語printf関数とほぼ同じ。エスケープが使えない。

成果物

構文

select printf('書式付き文字列', 値, ...);
文字列

書式指定子

指定子 対応する型 出力値
%c text 文字 %c
%s text 文字列 %s,%5s,%-5s
%d integer 整数(10進) %d,%-3d,%03d
%u integer 符号なし整数(10進) %u,%3u,%03u
%o integer 整数(8進) %o,%03o
%x integer 整数(16進)小文字 %x,%04x
%X integer 整数(16進)大文字 %X,%04X
%f real 実数 %f,%5.2f
%e real 実数(指数表示) %e,%5.3e
%g real 実数(最適な形式) %g
%ld integer 倍精度整数(10進) %ld,%-10ld
%lu integer 符号なし倍精度整数(10進) %lu,%10lu
%lo integer 倍精度整数(8進) %lo,%10lo
%lx integer 倍精度整数(16進) %lx,%08lx
%lf real 倍精度実数 %lf,%8.3lf

select printf('%c', 'ABC');
A
select printf('%c', 123);
1

select printf('%s', 'ABC');
ABC
select printf('%s', 123);
123
select printf('%5s', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
ABCDEFGHIJKLMNOPQRSTUVWXYZ
select printf('%5s', 'ABC');
  ABC
select printf('%-5s', 'ABC');
ABC  

select printf('%d', '123');
123
select printf('%d', '123.4');
123
select printf('%d', '-123.4');
-123
select printf('%d', '1+2');
1
select printf('%d', 'ABC');
0
select printf('%5d', '1234567890');
1234567890
select printf('%5d', '123');
  123
select printf('%-5d', '123');
123  
select printf('%05d', '123');
00123

select printf('%u', '123');
123
select printf('%u', '-123');
18446744073709551493
select printf('%u', '-123.4');
18446744073709551493

select printf('%o', 7);
7
select printf('%o', 8);
10
select printf('%3o', 8);
 10
select printf('%03o', 8);
010

select printf('%x', 15);
f
select printf('%x', 16);
10
select printf('%2x', 15);
 f
select printf('%02x', 15);
0f
select printf('%02X', 15);
0F

select printf('%f', 123.456789);
123.456789
select printf('%2.3f', 123.456789);
123.457
select printf('%4.3f', 123.456789);
123.457

select printf('%e', 1234567890);
1.234568e+09
select printf('%4.3e', 1234567890);
1.235e+09

select printf('%g', 1234567890);
1.23457e+09

エスケープ

 C言語ならできるが、SQLite3ではできない。そのまま出力されてしまう。

select printf('A\nB');
select printf('A\tB');
A\nB
A\tB

 SQL文脈で制御コードを入力するには以下のいずれかのようにする。

select printf('A
B');
select printf('A    B');
select printf('A' || cahr(10) || 'B');
select printf('A' || char(9) || 'B');
A
B
A   B

対象環境

$ uname -a
Linux raspberrypi 4.19.42-v7+ #1218 SMP Tue May 14 00:48:17 BST 2019 armv7l GNU/Linux

前回まで