jdbc连接Oracle数据库已经成功,现需要从数据库中查询一条记录,
在java中定义一条
String sql=“select * from where uni_no ='08051087' ”;
并将该sql作为参数传个java框架spring中的
this.getJdbcTemplate().query(sql, new ListExtractor());
可以顺利的得到值;而现实需要是uni_no为未知的参数,需要在sql中设计成?
于是我讲以上代码改成:
String uni_no=“08051087”;
String sql=“select * from where uni_no =?”;
this.getJdbcTemplate().query(sql, new String[]{uni_no},new ListExtractor());此事运行程序,程序不报错,但不能取出数据。注:this.getJdbcTemplate().query()方法为spring框架中管理jdbc的类 org.springframework.jdbc.core.support.JdbcDaoSupport自带的方法,该方法支持以上2种参数传入
在java中定义一条
String sql=“select * from where uni_no ='08051087' ”;
并将该sql作为参数传个java框架spring中的
this.getJdbcTemplate().query(sql, new ListExtractor());
可以顺利的得到值;而现实需要是uni_no为未知的参数,需要在sql中设计成?
于是我讲以上代码改成:
String uni_no=“08051087”;
String sql=“select * from where uni_no =?”;
this.getJdbcTemplate().query(sql, new String[]{uni_no},new ListExtractor());此事运行程序,程序不报错,但不能取出数据。注:this.getJdbcTemplate().query()方法为spring框架中管理jdbc的类 org.springframework.jdbc.core.support.JdbcDaoSupport自带的方法,该方法支持以上2种参数传入
String sql=“select * from where uni_no =?";
没有用过spring的你说的这个功能。
用过jdbc的相关方法。
jdbc中有个设置参数的方法。
setString(1,uni_no);//具体怎么样的忘记了,大概在jdbc上是这样的。
String uni_no=“08051087”;
String sql=“select * from where uni_no =‘?’”;
this.getJdbcTemplate().query(sql, new String[]{uni_no},new ListExtractor());但是却报错!
不行
取不到数据
我如果是写成死的String sql=“select * from where uni_no ='08051087' ”;
这样式可以执行的但是如果写成
String sql=“select * from where uni_no =08051087”;
这个也不能执行
方法是不是没有调用正确哟。
第二个参数应该是个object数组,至少还应该有一个参数来指出传入的参数的数据类型。
这个String sql=“select * from where uni_no =‘?’”;中
的单引号应该是不需要的,你去掉后得不到数据应该是其他地方的问题。
我还没有见过用jdbc时对"?"有用单引号的。
select * from where uni_no ='08051087'你确定可以正确执行?from后面的表名呢?
uni_no在表中定义为char(21byte)
请问是不是因为是这个原因呢?
如果是
那么在设计sql语句时,应该怎么传参数?
我用传统的jdbc写法也不行
把你用传统jdbc方式操作的代码贴出来看看。你光这样说,我们又没有看见你用传统方式操作数据库的代码,
因此我们也只有猜测了。
已经解决
需要在写sql语句时 加入:
sql=‘select * from student where TRIM(uni_no)= ?’;
这样就可以实现!!!
结账!!
create table test(str char(20));insert into test values ('hello');
commit;select str,length(str),length(trim(str)) from test;STR LENGTH(STR) LENGTH(TRIM(STR))
------------------------------ ----------- -----------------
hello 20 5
1 row selected.
select * from test where str = 'hello';STR
------------------------------
hello
1 row selected.-- 模擬你的情況
declare
v_str varchar2(20) := 'hello';
v_count number;
begin
select count(*) into v_count from test where str=v_str;
dbms_output.put_line(v_count);
end;-- dbms_output輸出是0declare
v_str varchar2(20) := 'hello';
v_count number;
begin
select count(*) into v_count from test where trim(str)=v_str;
dbms_output.put_line(v_count);
end;
-- dbms_output輸出是1-- 可以看出'hello ' != 'hello'
對於'hello',oracle將其視爲char類型,所以用Blank-Padded進行比較。就是當長度不同時,用空格填充短的那個值,再比較。所以相等。
而對於varchar2與char的比較,oracle用Nonpadded進行比較。即,當長度不同時,並不用空格填充短的那個值,所以不相等。詳細可以參考官方文檔:
http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/sql_elements002.htm
不错pengyanhui258
(pengyanhui258) 等 级:
结帖率:0.00%