我正在尝试与计算机上的数据库建立连接。数据库的密码是root,用户也是。我的项目库中有连接器jar文件,我有7.0 jre和jdk,表"客户端"在数据库" Testing1"存在,并且有1个条目,包含3个字段,
+--------------------+
| Tables_in_Testing1 |
+--------------------+
| clients |
| esk |
| files |
+--------------------+
客户表:
+----+------------------+-----------------------+
| id | PublicKey | Email |
+----+------------------+-----------------------+
| 1 | PublicKeyNumber1 | FirstClient@email.com |
+----+------------------+-----------------------+
以下是代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
class JDBCTest {
private static Connection con=null;
private static Statement st=null;
private static ResultSet rs=null;
public static void main(String args[])throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Testing1?user=root&password=root");
}catch (Exception e) {
System.out.println("e");
}
try{
st=con.createStatement();
rs=st.executeQuery("select * from clients");
while(rs.next()) {
System.out.println(rs.getString("Key"));
}
}
finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
}catch (SQLException e) {
System.out.println(e);
}
}
}
}
所有这些都会返回错误(在Eclipse中)
e
线程中的异常" main" java.lang.NullPointerException at JDBCTest.main(JDBCTest.java:22)
我认为它是因为没有与数据库的连接,所以 con 为空......但为什么呢?
答案 0 :(得分:0)
用e.printStackTrace()替换System.out.println(“e”),创建连接时会得到详细的异常。
它可能是ClassNotFoundException。
并且,如果密码不正确,请替换
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Testing1?user=root&password=root");
使用
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Testing1", "root, "root");
答案 1 :(得分:0)
我已经尝试过你的代码,它适用于我,只是对网址进行了一些更改。在获得连接时也会打印异常。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCTest{
private static Connection con = null;
private static Statement st = null;
private static ResultSet rs = null;
public static void main(String args[]) throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Testing1?user=root&password=root");
} catch (Exception e) {
System.out.println(e);
}
try {
st = con.createStatement();
rs = st.executeQuery("select * from users");
while (rs.next()) {
System.out.println(rs.getString("Key"));
}
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException e) {
System.out.println(e);
}
}
}
}