Exception in thread "main" java.lang.NullPointerException at 连接数据库.Con
publicclassConnectToJdbc{publicstaticvoidmain(String[]args){Connectioncon=null;java.s...
public class ConnectToJdbc {
public static void main(String[] args) {
Connection con = null;
java.sql.Statement sql;
ResultSet rs;
try {
Class.forName("com.mysql.jdbc.Driver");//加载JDBC驱动
} catch (Exception e) {
// TODO: handle exception
}
String uri = "jdbc:mysql://localhost:3306/students?useSSL=true";
String user = "root";
String password = "123456";
try {
con = DriverManager.getConnection(uri,user,password);
} catch (SQLException e) {
// TODO: handle exception
}
try {
sql = con.createStatement();
rs = sql.executeQuery("SELECT * FROM student");
while(rs.next()){
String num = rs.getString(1);
String name = rs.getString(2);
String sex = rs.getString(3);
int age = rs.getInt(4);
Reader zhuangye = rs.getCharacterStream(5);
System.out.printf("%s\t",num);
System.out.printf("%s\t",name);
System.out.printf("%s\t",sex);
System.out.printf("%s\t",age);
System.out.printf("%s\t",zhuangye);
}
con.close();
} catch (SQLException e) {
// TODO: handle exception
}
}
} 展开
public static void main(String[] args) {
Connection con = null;
java.sql.Statement sql;
ResultSet rs;
try {
Class.forName("com.mysql.jdbc.Driver");//加载JDBC驱动
} catch (Exception e) {
// TODO: handle exception
}
String uri = "jdbc:mysql://localhost:3306/students?useSSL=true";
String user = "root";
String password = "123456";
try {
con = DriverManager.getConnection(uri,user,password);
} catch (SQLException e) {
// TODO: handle exception
}
try {
sql = con.createStatement();
rs = sql.executeQuery("SELECT * FROM student");
while(rs.next()){
String num = rs.getString(1);
String name = rs.getString(2);
String sex = rs.getString(3);
int age = rs.getInt(4);
Reader zhuangye = rs.getCharacterStream(5);
System.out.printf("%s\t",num);
System.out.printf("%s\t",name);
System.out.printf("%s\t",sex);
System.out.printf("%s\t",age);
System.out.printf("%s\t",zhuangye);
}
con.close();
} catch (SQLException e) {
// TODO: handle exception
}
}
} 展开
1个回答
展开全部
Class.forName("com.mysql.jdbc.Driver").newInstance();//加载JDBC驱动
更多追问追答
追问
这里有什么问题吗
追答
加上 .newInstance()
另外
try {
con = DriverManager.getConnection(uri,user,password);
} catch (Exception e) {
e.printStackTrace();
}
改成这样.把异常打出来,不要把异常吃掉.你这里肯定是没取到数据库连接,然后你又把异常吃掉了
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询