【问题标题】:Getting null pointer exception in JDBC(mySql) program在 JDBC(mySql) 程序中获取空指针异常
【发布时间】:2014-08-04 07:46:57
【问题描述】:

我检查了所有内容,如用户名、密码、db_url、表名等,但我仍然得到这个输出---连接到数据库 创建语句 java.lang.NullPointerException

这是我的代码,(我使用的是 eclipse Kepler EE 和 MySQL 5.6.17.0)

import java.sql.*;
public class Demo {
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost/sample";
static final String USER="root" ;
static final String PASS="root";
public static void main(String[] args)
{
    Connection conn=null;
    Statement stmt=null;
    try
    {

        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("connecting to database");
        conn=DriverManager.getConnection(DB_URL, USER, PASS);
        System.out.println("creating statement");
        String sql="select * from sample";
        ResultSet rs=stmt.executeQuery(sql);
        while(rs.next())
        {
            int eid=rs.getInt("id");
            String ename=rs.getString("name");
            System.out.print(eid+"\t");
            System.out.print(ename);
            System.out.println("");

        }
        rs.close();
        stmt.close();
        conn.close();


    }catch(Exception e)
    {
        System.out.println(e);
    }
    finally
    {
        try
        {
            if(stmt!=null)
            {
                stmt.close();
            }
        }catch(Exception e)
        {
            System.out.println(e);
        }
        try
        {
            if(conn!=null)
            {
                conn.close();
            }
        }catch(Exception e)
        {
            System.out.println(e);
        }
    }
}
}

【问题讨论】:

  • 1) stmt 为空..2) 在您的DB_URL 中,您没有指定任何端口号

标签: java mysql eclipse jdbc nullpointerexception


【解决方案1】:

你设置了Statement stmt=null;,之后你永远不会初始化它。

【讨论】:

    【解决方案2】:

    你没有创建stmt对象

    stmt = conn.createStatement( );
    

    您必须在此行之前添加以上行ResultSet rs=stmt.executeQuery(sql);

    您正在对 null 对象执行查询。 所以得到NPE

    【讨论】:

      【解决方案3】:

      我认为您的声明尚未成立。它始终为空。

      我认为你应该使用这个:

      stmt = conn.createStatement( );
      

      【讨论】:

        猜你喜欢
        • 2013-07-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多