這篇文章主要介紹了PostgreSQL 實(shí)現(xiàn)sql放入文件批量執(zhí)行,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧。
PostgreSQL sql放入文件,登入數(shù)據(jù)庫(kù)之后批量執(zhí)行
1. 建立測(cè)試sql:
vi aa.sql插入:猜測(cè)每條sql語(yǔ)句是用;分隔的,function中的多個(gè);也會(huì)自動(dòng)識(shí)別。
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自動(dòng)識(shí)別的目錄,當(dāng)然也可以放在任意目錄,比如/home/postgres/aa.sql)
3. 切換用戶登入
1
2su postgrespsql postgres
4. 執(zhí)行:當(dāng)輸入i時(shí)候,會(huì)自動(dòng)檢測(cè)到./src/postgresql-9.3.5/src/tutorial下的文件,PostgreSQL的測(cè)試?yán)右卜旁诖四夸浵?/p>
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 |
第二個(gè)例子:
vi bb.sql:寫入一個(gè)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();
執(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í)行
1pslq -d postgres -U postgres -f /home/postgres/aa.sql
補(bǔ)充:PostgreSQL - 用psql 運(yùn)行SQL文件
對(duì)于預(yù)先寫好的SQL文件,比如/home/user1/updateMyData.sql, 可以有兩種方式來(lái)運(yùn)行這個(gè)SQL文件。
方式一:
連接db后執(zhí)行SQL文件
首先通過(guò)psql連接到對(duì)應(yīng)的db:
1psql -d db1 -U userA
接著輸入密碼,進(jìn)入數(shù)據(jù)庫(kù)后,輸入:
1i /pathA/xxx.sql
這里有個(gè)問(wèn)題,如果你把SQL文件的路徑里的路徑分隔符寫成了,會(huì)報(bào)錯(cuò)說(shuō)Permission denied。
這里的文件路徑必須使用Linux平臺(tái)下的路徑分隔符/,否則會(huì)報(bào)錯(cuò)。
方式二:
直接通過(guò)psql命令執(zhí)行SQL文件
這種方式無(wú)需先登錄數(shù)據(jù)庫(kù),直接用一個(gè)命令就可以了:
1psql -d db1 -U userA -f /pathA/xxx.sql
接著輸入密碼即可執(zhí)行SQL文件到對(duì)應(yīng)的db里。