如何使用JDBC检索数据 [英] How to retrieve data using JDBC

查看:105
本文介绍了如何使用JDBC检索数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试以下代码.

I have been trying with the following code.

正在建立连接.但是resultSet变成空的(不是null),而数据库中有两个相同的条目(每个2个字段).

The connection is being made. But the resultSet is coming as empty (not null), whereas there are a couple of entries (2 fields each) in the database for the same.

它不输入while条件.我是JDBC的新手,请帮忙!

It does not enter the while condition. I'm new to JDBC, please help!

我的代码是:

import java.sql.*;

public class JDBCTest123
{

    public static void main(String[] args)
    {
        System.out.println("oracle Connect Example.");
        Connection conn = null;
        String url = "jdbc:oracle:thin:@127.0.0.1:1521:XE";
        String driver = "oracle.jdbc.driver.OracleDriver";
        String userName = "system";
        String password = "mumpymamai";
        Statement stmt = null;
        String query = "select * from table1";  
        try
        {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, userName, password);
            stmt = conn.createStatement();
            System.out.println("Connected to the database");
            ResultSet rs = stmt.executeQuery(query);
            while (rs.next())
            {
                System.out.println(rs.getString(1));
                System.out.println(rs.getString(2));
            }
            conn.close();
            System.out.println("Disconnected from database");
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

输出为:

oracle Connect Example.
Connected to the database
Disconnected from database

推荐答案

建议很少.我建议您使用PreparedStatements更快,更安全.

So few suggestions. I recommend to you use PreparedStatements which are more faster and safer.

PreparedStatement ps = null;
conn = DriverManager.getConnection(url, userName, password);
ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next())
{
   // do some work
}

第二个建议,在finally块中调用close()方法,因为应用程序可能崩溃,然后您的连接不会关闭.最终,保证将始终被调用.

Second suggestion, call close() method in finally block, because application may crash and then your connection won't be closed. Finally block guarantees that will be always called.


第三条建议,如果没有Exception不能正常工作,可能是您的表空了.


Third suggestion if it doesn't work without Exception, probably you have empty table.

这篇关于如何使用JDBC检索数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆