用JAVA如何来查询数据库里面相关的数据

id name pid
1 南京
2 鼓楼区 1
3 下关区 1
4 大厂区 1
6 鼓楼区XX1 2
7 鼓楼区XX2 2
8 大厂区XX1 4
9 北京
10 北京朝阳区 9

我输入id=1那么就能够查到
1 南京
2 鼓楼区 1
3 下关区 1
4 大厂区 1
6 鼓楼区XX1 2
7 鼓楼区XX2 2
8 大厂区XX1 4

输入id=2
2 鼓楼区 1
6 鼓楼区XX1 2
7 鼓楼区XX2 2

输入id=9
9 北京
10 北京朝阳区 9
如何针对以上问题编制JAVA程序
谢谢各位的答案,但是我试了下,好像只能得到部分结果,例如:select * from mytable where id = 1 or pid = 1 得到的结果如下:
id name pid
1 南京
2 鼓楼区 1
3 下关区 1
4 大厂区 1
以下结果还是不能得到啊
6 鼓楼区XX1 2
7 鼓楼区XX2 2
8 大厂区XX1 4

你的意思就是根据id 找数据本身以及他的叶子节点。 假设你的表叫location
rs : ResultSet stmt: Statement

public ResultSet getLocation(int id) {
String sql = "select id, name, pid from location where id = " + id + "or pid = " + id;

rs = stmt.executeQuery(sql);
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-02-19
用jdbc喽
public static void main(String[] args) {

/*
* 获得配置库的dburl,dbDriver
*/
String dbUrl="jdbc:informix-sqli://localhost:8898/test2:INFORMIXSERVER=onjz1;user=aaa;password=bbb;LANG=en_US";
String dbDriver="com.informix.jdbc.IfxDriver";
String selectSql="select id,name,pid from 表 where id=?";
Connection conn=null;
//Statement ps=null;
int j=0;
try{
DriverManager.registerDriver((Driver)Class.forName(dbDriver).newInstance());
conn=DriverManager.getConnection(dbUrl);

ResultSet rs = stmt.executeQuery(selectSql);
while(rs.next){
//分别拿取值 就好
}
}
第2个回答  2009-02-22
看你的问法,估计sql语句和jdbc都没有学,没学的话讲的比较麻烦,单纯语句的话
1:select * from 表 where id=1
2:select * from 表 where id= 1 or pid = 1
3:select * from 表 where id= 9 or pid = 9
补充:你鼓楼区那个后面的pid是12(十二)吧~那样没法选
第3个回答  2009-02-19
你这个是全字段模糊查询吧 select * from mytable where id=1 or name like '%1%' or pid=1;

但是“7 鼓楼区XX2 2” 应该在查询1 的时候怎么也查不到的
第4个回答  2009-02-19
看了好一会儿 终于明白你的意思了。
你输入一个查询条件 这个条件只要id或pid任意一个满足条件就能够查询出来。
Java实现很简单就是获取你的查询条件。不在赘述
SQL:select * from 表名 where id = 参数 or pid = 参数
第5个回答  2009-02-19
差点被你给搞糊涂了,看下数据库吧,SQL语句学下!
相似回答