package com.cg.tr.jdbc;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.cg.trg.utilself.DBUtilSelf;
public class MenuBase {
public static void main(String[] args) {
Connection connection = DBUtilSelf.openConnection();
System.out.println("Connection opened");
String sql="SELECT BNUM FROM BOOK";
try
{
Statement st=connection.createStatement();
ResultSet rs=st.executeQuery(sql);
System.out.println("Book details");
while(rs.next())
{
System.out.print(rs.getInt("BNUM")+"\t");
System.out.print(rs.getString("BNAME")+"\t");
System.out.print(rs.getFloat("BPRICE")+"\t");
System.out.print(rs.getString("BAUTHOR")+"\t");
System.out.println();
}
}
catch(SQLException e)
{
e.printStackTrace();
}
finally
{
DBUtilSelf.closeConnection();
}
}
}
在eclipse上运行时,此代码不会从oracle中的表中打印数据。 输出是:
连接已打开 书籍详情
它没有进入while循环。没有生成任何异常。我已经确保表中的列名被正确写入。它还没有提供输出
package com.cg.trg.utilself;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class DBUtilSelf
{
static Connection connection;
static String url;
static String username;
static String password;
static
{
//load properties file...
Properties prop =new Properties();
FileInputStream fis;
try
{
fis=new FileInputStream("jdbc.properties");
prop.load(fis);
}
catch(IOException e)
{
System.out.println("Problem while loading properties file:"+e.getMessage());
}
url=prop.getProperty("url");
username=prop.getProperty("username");
password=prop.getProperty("password");
}
public static Connection openConnection()
{
try
{
connection=DriverManager.getConnection(url,username,password);
}
catch(SQLException e)
{
System.out.println("Error while opening connection"+e.getMessage());
}
return connection;
}
public static void closeConnection()
{
if(connection!=null)
{
try
{
connection.close();
}
catch(SQLException e)
{
System.out.println("Error while closing connection:"+e.getMessage());
}
}
}
}
这是DBUtilSelf.java文件
答案 0 :(得分:0)
代码是正确的,但唯一的问题是在sql中创建表后,它没有被提交。在sql中使用提交查询会保存数据库中的更改,以便通过jdbc可以看到它们。