1、导入MySQL-JDBC依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
2、实现代码连接
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class PolarDBJdbcDemo {
//数据库连接地址
private final String host = "host";
//账号
private final String user = "user";
//密码
private final String password = "password";
//端口
private final String port = "3306";
//数据库名称
private final String database = "db";
public void run() throws Exception {
Connection connect = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Properties props = new Properties();
props.put("user", user);
props.put("password", password);
String url = "jdbc:mysql://" + host + ":" + port + "/" + database+"?useSSL=false";
connect = DriverManager.getConnection(url, props);
String sql = "select * from dbTable";
preparedStatement = connect.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
System.out.println("id:" + resultSet.getInt(1));
System.out.println("name:" + resultSet.getString(2));
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
try {
if (resultSet != null)
resultSet.close();
if (statement != null)
statement.close();
if (connect != null)
connect.close();
} catch (SQLException e) {
e.printStackTrace();
throw e;
}
}
}
public static void main(String[] args) throws Exception {
PolarDBJdbcDemo demo = new PolarDBJdbcDemo();
demo.run();
}
}
3、查看结果