我在这个论坛上遇到了同样类型的问题,但是他们的解决方案在这里没有帮助。我试图在尝试连接到MySql工作台时在java中运行以下代码:
import java.sql.*;
public class DBConnection {
public static void main(String[] args)
{
Connection con = null;
PreparedStatement st =null;
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/world","root","password");
String sql = "select * from city where id = 1";
st = con.prepareStatement(sql); <---- here the error is shown
ResultSet rs = st.executeQuery();
while(rs.next())
{
int id = rs.getInt("ID");
String Name = rs.getString("Name");
String CountryCode = rs.getString("CountryCode");
String District = rs.getString("District");
int Population = rs.getInt("Population");
System.out.println(id);
System.out.println(Name);
System.out.println(CountryCode);
System.out.println(District);
System.out.println(Population);
}
rs.close();
st.close();
con.close();
}catch(Exception e)
{
e.printStackTrace();
}finally
{
try{
if(st!=null)
st.close();
}catch(SQLException se2){
}
try{
if(con!=null)
con.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
我主要收到以下错误:
--> PreparedStatement.java:4063 com.mysql.jdbc.PreparedStatement.toString()
--> PreparedStatement.java:587 com.mysql.jdbc.PreparedStatement.asSql()
--> PreparedStatement.java:591
com.mysql.jdbc.PreparedStatement.asSql(false)
java.lang.NullPointerException
at com.mysql.jdbc.PreparedStatement.asSql(PreparedStatement.java:649)
at com.mysql.jdbc.PreparedStatement.asSql(PreparedStatement.java:587)
at com.mysql.jdbc.PreparedStatement.toString(PreparedStatement.java:4068)
at java.lang.String.valueOf(Unknown Source)
at java.lang.StringBuffer.append(Unknown Source)
at com.mysql.jdbc.trace.Tracer.printParameters(Tracer.aj:240)
at com.mysql.jdbc.trace.Tracer.printEntering(Tracer.aj:167)
at com.mysql.jdbc.trace.Tracer.entry(Tracer.aj:126)
at com.mysql.jdbc.trace.Tracer.ajc$before$com_mysql_jdbc_trace_Tracer$1$f51c62b8(Tracer.aj:45)
at com.mysql.jdbc.Connection.registerStatement(Connection.java)
at com.mysql.jdbc.Statement.<init>(Statement.java:270)
at com.mysql.jdbc.PreparedStatement.<init>(PreparedStatement.java:500)
at com.mysql.jdbc.Connection.clientPrepareStatement(Connection.java:2187)
at com.mysql.jdbc.Connection.prepareStatement(Connection.java:4829)
at com.mysql.jdbc.Connection.prepareStatement(Connection.java:4734)
at Filereader.DBConnection.main(DBConnection.java:19)
--> Connection.java:2199 com.mysql.jdbc.Connection.close()
--> Connection.java:4892 com.mysql.jdbc.Connection.realClose(true, true, false, null)
--> Connection.java:4343 com.mysql.jdbc.Connection.isClosed()
代码中有什么问题?据我所知,DB Connectivity的预备语句写得正确,Sql查询格式似乎也没问题。