我正在尝试连接到我计算机上的数据库。数据库的密码是root,用户也是如此。我的项目库中有连接器 jar 文件,我有 7.0 jre 和 jdk,数据库“Testing1”中的表“clients”存在,并且有 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
Exception in thread "main" java.lang.NullPointerException at JDBCTest.main(JDBCTest.java:22)
我认为这是因为没有与数据库的连接,所以con为空......但为什么?
最佳答案
我已经尝试过你的代码,它对我有用,只是对网址做了一些更改。获取连接时也会打印异常。
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);
}
}
}
}
关于java - MySQL 与 JDBC 的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26770083/