无法连接到服务器意味着代码不输出任何内容。我认为,问题在于获得连接(即使我更改登录或通过)。顺便说一下,jdbc-driver被加载了(我没有单独安装它,它默认是用MySQL安装的)。 '用户' table位于新创建的数据库中。请说明该怎么做:
import java.sql.*;
import java.sql.Connection;
import java.sql.Statement;
public class DBConn {
public static void main(String[] args) {
Connection conn = null;
Statement statement = null;
ResultSet resultSet = null;
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/users";
conn = DriverManager.getConnection(url, "root", "1111");
statement = conn.createStatement();
resultSet = statement.executeQuery("SELECT * FROM users");
while(resultSet.next()){
System.out.println(resultSet.getInt("user_id") + ":" + resultSet.getString("usersName"));
}
} catch (ClassNotFoundException e){
e.printStackTrace();
} catch (SQLException e){
e.printStackTrace();
} finally {
try {
if (resultSet != null) resultSet.close();
if (statement != null) statement.close();
if (conn != null) conn.close();
} catch (SQLException e){
e.printStackTrace();
}
}
}
}
答案 0 :(得分:0)
按照步骤操作,否则您的代码就可以了:
mysql-connector-java-xxx
库users
,希望不要在下面相应地更改它
行: String url = "jdbc:mysql://localhost:3306/<put your Database Name>";