简体   繁体   English

我无法使用Java连接到数据库

[英]I can't connect to my database using java

Connection conn = null;
Statement stmt=null;
ResultSet rset=null;
String jdbc_url="jdbc:oracle:thin:hr/hr@bassam-desktop:1521:XE";
String query="";
try
{
    DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
    conn=DriverManager.getConnection(jdbc_url);
    stmt=(Statement) conn.createStatement();
    query="select first_name" +"from employees"+"where employeed_id=100";
    rset=stmt.executeQuery(query);
    System.out.println(rset.getString(1));


}
catch(SQLException | NumberFormatException e)
        {
            System.out.println("result error");
        }
finally{
    try{
        rset.close();
        stmt.close();
        conn.close();

    }
    catch(Exception e)
    {
        System.out.println("Error in closing");
    }
}

I'm getting both errors in the results window, what is the problem? 我在结果窗口中遇到两个错误,这是什么问题? hr password is correct, my host name is correct, isn't it the one you get from "Computer Name" after you right click on "My Computer" in windows xp ? hr密码正确,我的主机名正确,这不是在Windows XP中右键单击“我的电脑”后从“计算机名”获得的密码吗?

Edit: After using e.getMessage(), i got this.. 编辑:使用e.getMessage()后,我得到了..

result error, ResultSet.next was not called

The error message of the exception, that you have put in the comments, tells you what's wrong: 您已在注释中添加了异常的错误消息,告诉您出了什么问题:

result error, ResultSet.next was not called 结果错误,未调用ResultSet.next

You forgot to call ResultSet.next() before accessing the first row of the result set: 您忘记了在访问结果集的第一行之前调用ResultSet.next():

if (rset.next()) {
    System.out.println(rset.getString(1));
}

Because you're using Netbeans IDE, you can try connecting with their built in tool . 因为您使用的是Netbeans IDE,所以可以尝试使用其内置工具进行连接。 That should help you get the jdbc_url right (which is almost certainly the problem). 这应该可以帮助您正确设置jdbc_url (几乎可以肯定是问题所在)。 Also, don't forget to download and include in your classpath the ojdbc6.jar (which would definitely be the problem if you're not including it). 另外,不要忘记下载ojdbc6.jar并将其包含在您的类路径中(如果您不包含它,那肯定是问题所在)。

The e variable represent the exception. e变量表示异常。 try to print the e.getMessage() or print the stack trace with e.printStackTrace() to understand better the problem. 尝试打印e.getMessage()或使用e.printStackTrace()打印堆栈跟踪以更好地理解问题。

 ResultSet rset = stmt.executeQuery();
 while(rset.next()){
     //Code that works with results
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM