您好,登錄后才能下訂單哦!
如何在PostgreSQL中批量執(zhí)行sql文件?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
1. 建立測試sql:
vi aa.sql
插入:猜測每條sql語句是用;分隔的,function中的多個;也會自動識別。
create table tb1(id integer); insert into tb1 select generate_series(1,10); select * from tb1; delete from tb1 where id<3; select * from tb1;
2. 將aa.sql放入 ./src/postgresql-9.3.5/src/tutorial下(./src/postgresql-9.3.5/src/tutorial是PostgreSQL自動識別的目錄,當然也可以放在任意目錄,比如/home/postgres/aa.sql)
3. 切換用戶登入
su postgres psql postgres
4. 執(zhí)行:當輸入\i時候,會自動檢測到./src/postgresql-9.3.5/src/tutorial下的文件,PostgreSQL的測試例子也放在此目錄下
postgres=# \i aa.sql (\i /home/postgres/aa.sql) id | name ----+------ 1 | join 2 | join 3 | join 4 | join 5 | join 6 | join 7 | join 8 | join 9 | join 10 | join (10 rows) CREATE TABLE INSERT 0 10 id ---- 1 2 3 4 5 6 7 8 9 10 (10 rows) DELETE 2 id ---- 3 4 5 6 7 8 9 10 (8 rows) postgres=#
postgres=# \d tb1 Table "public.tb1" Column | Type | Modifiers --------+---------+----------- id | integer |
第二個例子:
vi bb.sql:
寫入一個function:
create function func1()returns void as $$ declare begin delete from person where id>5; delete from tb1 where id>5; end $$language plpgsql; select func1();
切換到postgres,登入之后執(zhí)行:
執(zhí)行前:
postgres=# select * from person ; id | name ----+------ 1 | join 2 | join 3 | join 4 | join 5 | join 6 | join 7 | join 8 | join 9 | join 10 | join (10 rows) postgres=# select * from tb1 ; id ---- 3 4 5 6 7 8 9 10 (8 rows)
執(zhí)行:
postgres=# \i bb.sql CREATE FUNCTION func1 ------- (1 row)
執(zhí)行后:
postgres=# select * from person ; id | name ----+------ 1 | join 2 | join 3 | join 4 | join 5 | join (5 rows) postgres=# select * from tb1 ; id ---- 3 4 5 (3 rows) postgres=#
5. 也可以使用psql命令執(zhí)行
pslq -d postgres -U postgres -f /home/postgres/aa.sql
補充:PostgreSQL - 用psql 運行SQL文件
對于預先寫好的SQL文件,比如/home/user1/updateMyData.sql, 可以有兩種方式來運行這個SQL文件。
連接db后執(zhí)行SQL文件
首先通過psql連接到對應的db:
psql -d db1 -U userA
接著輸入密碼,進入數(shù)據庫后,輸入:
\i /pathA/xxx.sql
這里有個問題,如果你把SQL文件的路徑里的路徑分隔符寫成了\,會報錯說Permission denied。
這里的文件路徑必須使用Linux平臺下的路徑分隔符/,否則會報錯。
直接通過psql命令執(zhí)行SQL文件
這種方式無需先登錄數(shù)據庫,直接用一個命令就可以了:
psql -d db1 -U userA -f /pathA/xxx.sql
接著輸入密碼即可執(zhí)行SQL文件到對應的db里。
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業(yè)資訊頻道,感謝您對億速云的支持。
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。