[英]Getting null pointer exception in JDBC(mySql) program
我檢查了所有內容,例如用戶名,密碼,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);
}
}
}
}
您沒有創建stmt
對象
stmt = conn.createStatement( );
您必須在此行之前添加以上行ResultSet rs=stmt.executeQuery(sql);
您正在對null
對象執行查詢。 因此獲得NPE
我認為您的陳述不成立。 始終為空。
我認為您應該使用此:
stmt = conn.createStatement( );
您設置Statement stmt=null;
而且您以后再也不會初始化它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.