gpt4 book ai didi

java - JDBC(mySql)程序中出现空指针异常

转载 作者:行者123 更新时间:2023-11-30 00:09:25 26 4
gpt4 key购买 nike

我检查了用户名、密码、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 = conn.createStatement( );

关于java - JDBC(mySql)程序中出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24210590/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com