运行时的代码将打开jdbc连接,但不会打印表数据.此代码有什么问题? [英] The code when run opens the jdbc connection but it is not printing the table data.What is wrong with this code?
问题描述
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中的表中打印数据. 输出为:
This code when run on eclipse does not print the data from table in oracle. The output is:
连接已打开 图书详细信息
Connection opened Book details
它不会进入while循环.不会产生任何异常.我已确保正确写入表中的列名.仍然不会给出输出
It does not enter the while loop.Neither any exception is generated.I have made sure that column names from the table are written correctly.Still it does not give output
包com.cg.trg.utilself;
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文件
This is the DBUtilSelf.java file
推荐答案
该代码是正确的,但是唯一的问题是在sql中创建表后,该提交未被提交.在sql中使用commit查询可将更改保存在数据库中,以便可以通过jdbc看到更改.
The code was right but the only problem was that after creating table in sql,it was not commited. Using the commit query in sql saves the changes in the database so that they can be visible through jdbc.
这篇关于运行时的代码将打开jdbc连接,但不会打印表数据.此代码有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!