postgreSQL學(xué)習(xí)筆記
歡迎大家指出問題!
版本從6.0開始支持SQL解釋器
安裝一路下一步。
1.創(chuàng)建數(shù)據(jù)庫
//命令行操作
createdb database_name;
CREATE DATABASE database_name;
psql -l //展示所有數(shù)據(jù)庫
psql database_name //進(jìn)入數(shù)據(jù)庫
2.刪除數(shù)據(jù)庫
dropdb database;
DROP DATABASE database_name;
3.創(chuàng)建表
create table 表名 (title varchar(255), content text);
//修改表名
alter table posts rename to 表名;
//查看表信息(結(jié)構(gòu))
\d 表名
//執(zhí)行這個sql文件
\i a.sql
//切換數(shù)據(jù)顯示方式(橫向和縱向顯示)
\x
create table posts (
id serial primary key,
title varchar(255) not null,
content text check(length(content) > 3),
is_draft boolean default FALSE,
created_date timestamp default 'now');
CREATE TABLE public.students
(
id integer NOT NULL,
name character(128),
subjects character(1),
CONSTRAINT student2_pkey PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
ALTER TABLE public.students
OWNER TO postgres;
COMMENT ON TABLE public.students
IS '這是一個學(xué)生信息表';
案例表:
4.刪除表
5.數(shù)據(jù)類型
數(shù)值型:
integer real serial(序列型,一般用于自增字段)
文字型:
char varchar text
布爾型:
boolean
日期型:
date time timestamp
特色類型:
Array inet(網(wǎng)口類型) JSON XML
6.添加表約束
unique
:所在數(shù)據(jù)中值必須唯一
check
:字段設(shè)置條件,可以指定函數(shù)check(length(content) > 3)必須超過3個字符
default
:字段默認(rèn)值
7.INSERT語句
insert into 表名(cloum1,cloum2) value(a,b);
8.數(shù)據(jù)抽出選項:
order by asc
升序 desc
降序
limit
限制返回數(shù)據(jù)條數(shù)
offset
偏移量(從哪條數(shù)據(jù)開始)
//分頁查詢limit和offset結(jié)合使用。
select * from users order by score desc limit 3;
select * from users order by score desc limit 3 offset 3;
9.統(tǒng)計抽出數(shù)據(jù)
distinct
去重
group by/having
(在group by
之后進(jìn)行再次篩選) 分組
select team,max(score) from users group by team having max(score)>25 order by max(score);
10.方便的函數(shù)
length concat
(連接兩個字符串) alias
(別名) substring
(截取字符串) random
select player,length(player) from users;
select player,concat(player,"/",team) from users;
select player,concat(player,"/",team) as "球員信息" from users;
select concat('我',substring(team,1,1)) as "球隊首文字" from users;
//隨機(jī)抽獎
select player from users order by random() limit 1;
11.更新和刪除
update [table] set [field=newvalue,…] where …
delete from [table] where …
eg:
update users set score = score + 100 where team IN ("勇士","騎士");
12.變更表結(jié)構(gòu)
//alter table [tablename] …
//給表添加一條fullname字段
alter table users add fullname varchar(255);
//給哪個表的字段建索引(索引提高查詢效率,但是增刪效果不好)
create index 索引名 on users(字段名);
//刪除索引
drop index 索引名;
//修改列名
alter table users rename player to nba_player;
//修改字段的的長度
alter table users alter nba_player type varchar(128);
13.操作多個表
//兩表的關(guān)聯(lián)查詢
select users.player,twitters.content from users,twitters where users.id = twitters.user_id;
//別名
select u.player,t.content from users as u,twitters as t where u.id = t.user_id;
14.使用視圖
視圖:視圖就是一個select語句,把業(yè)務(wù)系統(tǒng)中常用的select語句簡化成一個類似于表的對象,便于簡單讀取和開發(fā)。 (對于經(jīng)常使用的select語句建立視圖便于編碼和管理)
//創(chuàng)建一個視圖(通過 \dv 查看視圖描述)
create view curry_twitters as select u.player,t.content from users as u,twitters as t where u.id = t.user_id;
//要進(jìn)行查詢時
select * from curry_twitters;
//刪除視圖
drop view curry_twitters;
15.使用事務(wù)
數(shù)據(jù)庫事務(wù):是指作為單個邏輯工作單元執(zhí)行的一系列操作,要么一起成功,要么一起失敗。必須滿足ACID(原子性、 一致性、隔離性、持久性)
PostgreSQL
數(shù)據(jù)庫事務(wù)使用
begin
開啟事務(wù)
commit
提交
rollback
回滾
eg:
begin;
update users set score = 50 where player = '庫里';
update users set score = 60 where player = '哈登';
commit; //如果不想跟新可以 rollback;
補(bǔ)充:postgresql一般crud存儲過程參考
這里是一份經(jīng)過再三調(diào)試測試而成功的postgres數(shù)據(jù)庫單表crud存儲過程,請注意,對于多結(jié)果的返回方式,請查看getPageByCondition的書寫方式,用的是refcursor,返回一個cursor,同時可以返回其他out,inout參數(shù),但是refcursor必須在事務(wù)中調(diào)用,所以java端的調(diào)用過程需要注意,好吧,我同時放出一份dal樣板,大家可以直接copy來用。
/******************************************************************
* 表名:test3
* Made by 碼農(nóng)下的天橋
******************************************************************/
--use MYDB;--你可以指定自己的數(shù)據(jù)庫
/******************************************************************
****************************各種常用查詢***************************
******************************************************************/
------------------------------------
--用途:復(fù)雜形式的查詢語句,用于查詢分頁數(shù)據(jù)。
--這個是泛用型的,假如你要根據(jù)用戶輸入去查詢,那么最好不要用這個了,
--以免出現(xiàn)sql注入。
--參數(shù)說明:
---_offset int 需要取的記錄的開始位置
---_limit int 需要獲取記錄的總條數(shù),針對分頁而言,就是分頁的pagesize。
---_columns varchar(800) 需要獲取的字段
---_where varchar(800) 需要過濾的條件譬如: where id10 可以帶where,不過建議不要帶。
---_orderby varchar(800) 需要進(jìn)行排序的提交,譬如:order by id
---_totalCount int 返回總共記錄條數(shù)。
---_totalPages int 返回總共頁數(shù)。
------------------------------------
create or replace function test3_getListByCondition(
INOUT pageindex INT,
INOUT pagesize INT,
IN _columns VARCHAR(800),
IN _where VARCHAR(800),
IN _orderby VARCHAR(800),
out _totalCount INT,
out _totalPages INT)
returns SETOF record
AS
$$
DECLARE condition_columns VARCHAR(800);
DECLARE condition_where varchar(800);
DECLARE condition_orderby VARCHAR(800);
DECLARE _dymatic_sql VARCHAR(1600);
DECLARE _beginNO INT;
DECLARE _dynamic_getCount varchar(1600);
DECLARE _theOffset INT;
DECLARE _tmpInt1 INT;
BEGIN
condition_where:=ltrim(rtrim(COALESCE(_where,'')));
condition_orderby:=ltrim(rtrim(COALESCE(_orderby,'order by t3id')));
condition_columns:=ltrim(rtrim(COALESCE(_columns,'*')));
--分析傳過來的參數(shù),構(gòu)造動態(tài)sql語句。
IF "character_length"(condition_where)>0 THEN
IF strpos(condition_where, 'where ')!=1 THEN
condition_where:='where ' || condition_where;
END IF;
END IF;
--order by 語句構(gòu)造
IF "character_length"(condition_orderby)>0 THEN
IF strpos(condition_orderby, 'order ')!=1 THEN
condition_orderby:='order by '||condition_orderby;
END IF;
END IF;
--判斷pageindex是否合法及pagesize是否合法
IF pageindex1 THEN
pageindex:=1;
END IF;
IF pagesize1 THEN
pagesize:=20;
END IF;
_dynamic_getCount:='select count(*) from test3 '||condition_where|| ' ' ;
EXECUTE _dynamic_getCount INTO _totalCount;
IF _totalCount1 THEN
pageindex:=1;
RETURN;
END IF;
--計算總共頁數(shù)
_tmpInt1:=_totalCount%pagesize;
IF _tmpInt1=0 THEN
_totalPages:=_totalCount / pagesize;
ELSE
_totalPages:=(_totalCount-_tmpInt1)/pagesize+1;
END IF;
IF _totalPages pageindex then
pageindex:=_totalPages;
END IF;
_theOffset:=(pageindex-1) * pagesize+1;
_dymatic_sql:='select '||condition_columns||' from test3 '||condition_where||' '||condition_orderby||' limit '||pagesize||' '|| ' offset '||_theOffset||' ';
--raise info '動態(tài)構(gòu)造語句為:%',_dymatic_sql;
return query EXECUTE _dymatic_sql;
END;
$$ language plpgsql VOLATILE;
------------------------------------
--用途:復(fù)雜形式的查詢語句,用于查詢多條記錄數(shù)據(jù)。
--這個是泛用型的,假如你要根據(jù)用戶輸入去查詢,那么最好不要用這個了,
--以免出現(xiàn)sql注入。
--參數(shù)說明:
---_offset int 需要取的記錄的開始位置
---_limit int 需要獲取記錄的總條數(shù),針對分頁而言,就是分頁的pagesize。
---_columns varchar(800) 需要獲取的字段
---_where varchar(800) 需要過濾的條件譬如: where id10 可以帶where,不過建議不要帶。
---_orderby varchar(800) 需要進(jìn)行排序的提交,譬如:order by id
---_totalCount int 返回總共記錄條數(shù)。
------------------------------------
create or replace function test3_getPageByCondition(
INOUT pageindex INT,
INOUT pagesize INT,
IN _columns VARCHAR(800),
IN _where VARCHAR(800),
IN _orderby VARCHAR(800),
out _totalCount INT,
out _totalPages INT,
out _refcursor refcursor
)
returns SETOF record
AS
$$
DECLARE condition_columns VARCHAR(800);
DECLARE condition_where varchar(800);
DECLARE condition_orderby VARCHAR(800);
DECLARE _dymatic_sql VARCHAR(1600);
DECLARE _beginNO INT;
DECLARE _dynamic_getCount varchar(1600);
DECLARE _theOffset INT;
DECLARE _tmpInt1 INT;
BEGIN
condition_where:=ltrim(rtrim(COALESCE(_where,'')));
condition_orderby:=ltrim(rtrim(COALESCE(_orderby,'order by t3id')));
condition_columns:=ltrim(rtrim(COALESCE(_columns,'*')));
--分析傳過來的參數(shù),構(gòu)造動態(tài)sql語句。
IF "character_length"(condition_where)>0 THEN
IF strpos(condition_where, 'where ')!=1 THEN
condition_where:='where ' || condition_where;
END IF;
END IF;
--order by 語句構(gòu)造
IF "character_length"(condition_orderby)>0 THEN
IF strpos(condition_orderby, 'order ')!=1 THEN
condition_orderby:='order by '||condition_orderby;
END IF;
END IF;
--判斷pageindex是否合法及pagesize是否合法
IF pageindex1 THEN
pageindex:=1;
END IF;
IF pagesize1 THEN
pagesize:=20;
END IF;
_dynamic_getCount:='select count(*) from test3 '||condition_where|| ' ' ;
EXECUTE _dynamic_getCount INTO _totalCount;
IF _totalCount1 THEN
pageindex:=1;
RETURN;
END IF;
--計算總共頁數(shù)
_tmpInt1:=_totalCount%pagesize;
IF _tmpInt1=0 THEN
_totalPages:=_totalCount / pagesize;
ELSE
_totalPages:=(_totalCount-_tmpInt1)/pagesize+1;
END IF;
IF _totalPages pageindex then
pageindex:=_totalPages;
END IF;
_theOffset:=(pageindex-1) * pagesize+1;
_dymatic_sql:='select '||condition_columns||' from test3 '||condition_where||' '||condition_orderby||' limit '||pagesize||' '|| ' offset '||_theOffset||' ';
--raise info '動態(tài)構(gòu)造語句為:%',_dymatic_sql;
open _refcursor for EXECUTE _dymatic_sql;
RETURN NEXT;
END;
$$ language plpgsql VOLATILE;
------------------------------------
--用途:獲取其中一條記錄
------------------------------------
create or replace function test3_getRecord(in _id integer)
returns SETOF test3
AS
$$
BEGIN
return query select * from test3 where t3id=_id LIMIT 1 OFFSET 0;
END;
$$ LANGUAGE plpgsql VOLATILE;
------------------------------------
--用途:復(fù)雜形式的查詢語句,用于查詢前面第幾條記錄,這個就相當(dāng)好了
--這個是泛用型的,假如你要根據(jù)用戶輸入去查詢,那么最好不要用這個了,
--以免出現(xiàn)sql注入。
--參數(shù)說明:
---_topN int 需要取的topN條記錄。
---_columns varchar(800) 需要獲取的字段
---_where varchar(800) 需要過濾的條件譬如: where id10 可以帶where,不過建議不要帶。
---_orderby varchar(800) 需要進(jìn)行排序的提交,譬如:order by id
------------------------------------
create or replace function test3_getTopNbyCondition(IN _topN int,IN _columns VARCHAR(800),IN _where VARCHAR(800),IN _orderby VARCHAR(800))
returns SETOF test3
AS
$$
DECLARE condition_columns VARCHAR(800);
DECLARE condition_where varchar(800);
DECLARE condition_orderby VARCHAR(800);
DECLARE _dymatic_sql VARCHAR(1600);
BEGIN
condition_where:=ltrim(rtrim(COALESCE(_where,'')));
condition_orderby:=ltrim(rtrim(COALESCE(_orderby,'order by t3id')));
condition_columns:=ltrim(rtrim(COALESCE(_columns,'*')));
--分析傳過來的參數(shù),構(gòu)造動態(tài)sql語句。
IF "character_length"(condition_where)>0 THEN
IF strpos(condition_where, 'where ')!=1 THEN
condition_where:='where ' || condition_where;
END IF;
END IF;
--order by 語句構(gòu)造
IF "character_length"(condition_orderby)>0 THEN
IF strpos(condition_orderby, 'order ')!=1 THEN
condition_orderby:='order by '||condition_orderby;
END IF;
END IF;
_dymatic_sql:='select '||condition_columns||' from test2 '||condition_where||' '||condition_orderby||' limit '||CAST(_topN as VARCHAR)|| ' offset 0 ';
--raise info '動態(tài)構(gòu)造語句為:%',_dymatic_sql;
return query EXECUTE _dymatic_sql;
END;
$$ language plpgsql VOLATILE;
/******************************************************************
*****************************記錄刪除******************************
******************************************************************/
------------------------------------
--用途:刪除多條記錄
------------------------------------
create or replace function test3_DeleteList(in ids VARCHAR(800),out status boolean,out msg VARCHAR(200))
returns record
AS
$$
DECLARE _arr_ids int[];
DECLARE _str_ids "text";
DECLARE _str_sql VARCHAR(1600);
DECLARE _effects int;
BEGIN
IF "character_length"(ids)1 THEN
status:=false;
msg:='沒有指定需要刪除的數(shù)據(jù)!';
return;
end if;
_arr_ids:=tools_str2intarray(ids, ',');
_str_ids:=tools_stringify(_arr_ids,',');
--pkey為主鍵,自增的整數(shù), @ 表示判斷pkey是不是在數(shù)組里面。是不是很方便?
/*動態(tài)構(gòu)造執(zhí)行*/
--_str_sql:='DELETE FROM test3 where t3id in ('||_str_ids||') ;';
--EXECUTE _str_sql;
/*直接執(zhí)行*/
delete from test3 where t3id =ANY( _arr_ids);
GET DIAGNOSTICS _effects = ROW_COUNT;
IF _effects>0 THEN
status:=true;
msg:='成功刪除'||_effects||'條記錄!';
ELSE
status:=false;
msg:='沒有刪除任何記錄!';
end if;
END
$$ LANGUAGE plpgsql VOLATILE;
/******************************************************************
****************************添加及編輯*****************************
******************************************************************/
------------------------------------
--用途:增加一條記錄
------------------------------------
create or replace function test3_Insert(
in __t3name varchar(400) ,
in __t_birthday date ,
in __myage smallint ,
in __isadmin boolean ,
in __myintro text ,
in __price float ,
out __t3id integer,
out _status boolean,
out _msg varchar(200))
returns record AS $$
BEGIN
Insert into test3
(
"t3name","t_birthday","myage","isadmin","myintro","price"
)
values(
__t3name,__t_birthday,__myage,__isadmin,__myintro,__price
);
/*判斷添加記錄是否成功。*/
if FOUND then
_status:=true;
_msg:='成功添加記錄.';
__t3id:=currval(pg_get_serial_sequence('test3', 't3id'));
else
_status:=false;
_msg:='無法添加記錄!';
end if;
end;
$$ LANGUAGE plpgsql VOLATILE;
------------------------------------
--用途:修改一條記錄
------------------------------------
create or replace function test3_Update(
in __t3name varchar(400) ,
in __t_birthday date ,
in __myage smallint ,
in __isadmin boolean ,
in __myintro text ,
in __price float ,
in __t3id integer,
out _status boolean,
out _msg varchar(200))
returns record AS $$
BEGIN
update test3 set
"t3name"=__t3name,"t_birthday"=__t_birthday,"myage"=__myage,"isadmin"=__isadmin,"myintro"=__myintro,"price"=__price where t3id=__t3id;
/*判斷保存記錄是否成功。*/
if FOUND then
_status:=true;
_msg:='成功保存記錄.';
else
_status:=false;
_msg:='無法保存記錄!';
end if;
end;
$$ LANGUAGE plpgsql VOLATILE;
對應(yīng)dal調(diào)用文件:
package EasisWeb.DAL;
import EasisWeb.config.DBPool;
import Easis.Common.StringUtil;
import Easis.util.DataRow;
import Easis.util.DataTable;
import Easis.util.DataTableHelper;
import java.util.Date;
import Easis.DBUtility.PooledConnection;
import java.sql.*;
import java.util.List;
import java.util.ArrayList;
import Easis.util.OperationResult;
import Easis.util.PagerResult;
import EasisWeb.Model.test3Model;
/**
* 這是利用CodeGen工具生成的自動訪問數(shù)據(jù)庫的一個模板,作者為“碼農(nóng)下的天橋”
*生成的類名稱:
* @author 碼農(nóng)下的天橋
* @version 1.00
*/
public class test3DAL {
/*表格各種column*/
public static final String col_t3id="test3";
public static final String col_t3name="test3";
public static final String col_t_birthday="test3";
public static final String col_myage="test3";
public static final String col_isadmin="test3";
public static final String col_myintro="test3";
public static final String col_price="test3";
public static final String PKColumn="t3id";
/**
*存儲過程名稱:test3_ListByCondition
*存儲過程參數(shù):
*@param pageindex
*@param pagesize
*@param columns 需要獲取的字段
*@param condition where條件語句
*@param orderColumn order by排序語句
*
*@return 分頁對象
*/
public PagerResult getPageListByCondition(int pageindex,int pagesize, String columns, String condition, String orderColumn){
PagerResult pres=new PagerResult();
//output參數(shù)定義
int _total = 0 ;
int _pagesize = 0 ;
int _pageindex = 0 ;
int _totalpages = 0 ;
//output參數(shù)定義結(jié)束
//調(diào)用存儲過程
DataTable res__datatable=new DataTable();
try{
PooledConnection __myconn=DBPool.getConnection();
__myconn.setAutoCommit(false); // return refcursor must within a transaction
CallableStatement _stmt=__myconn.prepareCall("{ call test3_getPageByCondition( ?, ?, ?, ?, ?, ?, ?, ?)}");
_stmt.setInt(1,pageindex);
_stmt.setInt(2,pagesize);
_stmt.registerOutParameter(1,Types.INTEGER);
_stmt.registerOutParameter(2,Types.INTEGER);
_stmt.setString(3,columns);
_stmt.setString(4,condition);
_stmt.setString(5,orderColumn);
_stmt.registerOutParameter(6, Types.INTEGER);
_stmt.registerOutParameter(7, Types.INTEGER);
_stmt.registerOutParameter(8,Types.OTHER);
_stmt.execute();
ResultSet __rslist=(ResultSet)_stmt.getObject(8);
res__datatable=DataTableHelper.rs2datatable(__rslist);
//取回參數(shù)
_total=_stmt.getInt(6);
pres.totalrecords=_total;
_pageindex=_stmt.getInt(1);
pres.totalrecords=_total;
_pagesize=_stmt.getInt(2);
pres.pageindex=_pageindex;
pres.pagesize=_pagesize;
_totalpages=_stmt.getInt(7);
pres.totalpages=_totalpages;
pres.datasource=res__datatable;
//--提交并還原
__myconn.commit();
__myconn.setAutoCommit(true); //返回游標(biāo)必須在一個事務(wù)中,提交完以后將autocommit還原。
//釋放資源
__rslist.close();
_stmt.close();
__myconn.close();}
catch (Exception __e){
System.out.println("在運行[test3DAL]的List_Condition時候出現(xiàn)錯誤。");
__e.printStackTrace();
}
return pres;
}
/**
*存儲過程名稱:test3_Insert
*存儲過程參數(shù):
*param t3id 【主鍵】
t3name
t_birthday
myage
isadmin
myintro
price
*
*@return
*/
public OperationResult Insert(test3Model model){
OperationResult __ores=new OperationResult();
/*output參數(shù)定義*/
int t3id = 0 ;
DataRow returnInfo=new DataRow();
boolean status = false ;
String message = "" ;
/*output參數(shù)定義結(jié)束*/
/*調(diào)用存儲過程*/
try{
PooledConnection __myconn=DBPool.getConnection();
CallableStatement _stmt=__myconn.prepareCall("{call test3_Insert(?,?,?,?,?,?,?,?,?)}");
_stmt.setObject(1,model.t3name,Types.VARCHAR);
_stmt.setObject(2,new Timestamp(model.t_birthday.getTime()),Types.DATE);
_stmt.setObject(3,model.myage,Types.SMALLINT);
_stmt.setObject(4,model.isadmin,Types.BOOLEAN);
_stmt.setObject(5,model.myintro,Types.VARCHAR);
_stmt.setObject(6,model.price,Types.FLOAT);
_stmt.registerOutParameter(7,Types.INTEGER,-1);
_stmt.registerOutParameter(8, Types.BOOLEAN,1);
_stmt.registerOutParameter(9, Types.VARCHAR,200);
_stmt.execute();
/*取回參數(shù)*/
t3id=_stmt.getInt(7);
status=_stmt.getBoolean(8);
message=_stmt.getString(9);
__ores.id= t3id;
__ores.status=status;
__ores.message=message;
/*釋放資源*/
_stmt.close();
__myconn.close();}
catch (Exception __e){
__e.printStackTrace();
__ores.message=__e.toString();
}
return __ores;
}
/**
*存儲過程名稱:test3_Update
*存儲過程參數(shù):
* t3id【主鍵】
t3name
t_birthday
myage
isadmin
myintro
price
*
*@return
*/
public OperationResult Update(test3Model model){
OperationResult __ores=new OperationResult();
/*output參數(shù)定義*/
boolean status = false ;
String message = "" ;
/*output參數(shù)定義結(jié)束*/
/*調(diào)用存儲過程*/
DataTable res__datatable=new DataTable();
try{
PooledConnection __myconn=DBPool.getConnection();
CallableStatement _stmt=__myconn.prepareCall("{ call test3_Update( ?,?,?,?,?,?,?,?,?)}");
_stmt.setObject(1,model.t3name,Types.VARCHAR);
_stmt.setObject(2,new Timestamp(model.t_birthday.getTime()),Types.DATE);
_stmt.setObject(3,model.myage,Types.SMALLINT);
_stmt.setObject(4,model.isadmin,Types.BOOLEAN);
_stmt.setObject(5,model.myintro,Types.VARCHAR);
_stmt.setObject(6,model.price,Types.FLOAT);
_stmt.setInt(7,model.t3id);
_stmt.registerOutParameter(8, Types.BOOLEAN,1);
_stmt.registerOutParameter(9, Types.VARCHAR,400);
_stmt.execute();
/*取回參數(shù)*/
status=_stmt.getBoolean(8);
message=_stmt.getString(9);
__ores.status=status;
__ores.message=message;
/*釋放資源*/
_stmt.close();
__myconn.close();}
catch (Exception __e){
__e.printStackTrace();
}
return __ores;
}
/**
*存儲過程名稱:test3_DeleteList
*存儲過程參數(shù):
*@param ids 【參數(shù)名稱:ids 參數(shù)類型:nvarchar 對應(yīng)java類型:String 長度:400 】
*
*@return
*/
public OperationResult DeleteList( String ids){
/*output參數(shù)定義*/
OperationResult __ores=new OperationResult();
boolean status = false ;
String message = "" ;
/*output參數(shù)定義結(jié)束*/
/*調(diào)用存儲過程*/
DataTable res__datatable=new DataTable();
try{
PooledConnection __myconn=DBPool.getConnection();
CallableStatement _stmt=__myconn.prepareCall("{ call test3_DeleteList( ?, ?, ?)}");
_stmt.setString(1,ids);
_stmt.registerOutParameter(2, Types.BOOLEAN,1);
_stmt.registerOutParameter(3, Types.VARCHAR,400);
_stmt.execute();
/*取回參數(shù)*/
status=_stmt.getBoolean(2);
message=_stmt.getString(3);
__ores.status=status;
__ores.message=message;
/*釋放資源*/
_stmt.close();
__myconn.close();}
catch (Exception __e){
__e.printStackTrace();
}
return __ores;
}
/**
*存儲過程名稱:test3_GetRecord
*存儲過程參數(shù):
*@param t3id 【參數(shù)名稱:id 參數(shù)類型:int 對應(yīng)java類型:int 長度:非字符類型 】
*
*@return DataTable對象。
*/
public test3Model GetRecord( int t3id ){
/*調(diào)用存儲過程*/
DataTable res__datatable=new DataTable();
test3Model model=new test3Model();
try{
PooledConnection __myconn=DBPool.getConnection();
CallableStatement _stmt=__myconn.prepareCall("{ call test3_GetRecord( ?)}");
_stmt.setInt(1,t3id);
ResultSet __rslist =_stmt.executeQuery();
res__datatable=DataTableHelper.rs2datatable(__rslist);
model=tryParseModel(res__datatable.get(0));
/*釋放資源*/
__rslist.close();
_stmt.close();
__myconn.close();}
catch (Exception __e){
__e.printStackTrace();
}
return model;
}
/**
*存儲過程名稱:test3_Top_Condition
*存儲過程參數(shù):
*@param topN 【參數(shù)名稱:topN 參數(shù)類型:int 對應(yīng)java類型:int 長度:非字符類型 】
*@param columns 【參數(shù)名稱:columns 參數(shù)類型:nvarchar 對應(yīng)java類型:String 長度:800 】
*@param condition 【參數(shù)名稱:condition 參數(shù)類型:nvarchar 對應(yīng)java類型:String 長度:800 】
*@param orderColumn 【參數(shù)名稱:orderColumn 參數(shù)類型:nvarchar 對應(yīng)java類型:String 長度:800 】
*
*@return DataTable對象。
*/
public DataTable Top_Condition( int topN, String columns, String condition, String orderColumn ){
/*調(diào)用存儲過程*/
DataTable res__datatable=new DataTable();
try{
PooledConnection __myconn=DBPool.getConnection();
CallableStatement _stmt=__myconn.prepareCall("{ call test3_Top_Condition( ?, ?, ?, ?)}");
_stmt.setInt(1,topN);
_stmt.setString(2,columns);
_stmt.setString(3,condition);
_stmt.setString(4,orderColumn);
ResultSet __rslist =_stmt.executeQuery();
res__datatable=DataTableHelper.rs2datatable(__rslist);
/*釋放資源*/
__rslist.close();
_stmt.close();
__myconn.close();}
catch (Exception __e){
__e.printStackTrace();
}
return res__datatable;
}
public test3Model tryParseModel(DataRow drow){
test3Model model=new test3Model();
if(drow==null){
return model;
}
/*
return "boolean";
return "Date";
return "double";
return "float";
return "int";
return "long";
return "String";
return "Object";
*/
/*嘗試賦值*/
model.t3id = drow.get("t3id").toInt();
model.t3name = drow.get("t3name").toString();
model.t_birthday = drow.get("t_birthday").toDate();
model.myage = drow.get("myage").toInt();
model.isadmin = drow.get("isadmin").toBoolean();
model.myintro = drow.get("myintro").toString();
model.price = drow.get("price").toFloat();
return model;
}
public Listtest3Model> tryParseList(ListDataRow> dataList){
Listtest3Model> modellist=new ArrayListtest3Model>();
if(dataList==null){
return modellist;
}
for(DataRow drow :dataList){
modellist.add(tryParseModel(drow));
}
return modellist;
}
}
這只是一份模板而已。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
您可能感興趣的文章:- PostgreSQL timestamp踩坑記錄與填坑指南
- PostgreSQL的upsert實例操作(insert on conflict do)
- PostgreSQL 字符串拆分與合并案例
- postgresql合并string_agg函數(shù)的實例
- PostgreSQL 序列增刪改案例
- postgresql重置序列起始值的操作
- postgresql 實現(xiàn)得到時間對應(yīng)周的周一案例