maven包依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
连接查询
初始化驱动
static {
try {
Class.forName(driverclass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
- jdbc4.0后, 驱动加载可省略, DriverManager初始化会隐式加载
参数
private static String user = "root";
private static String pwd = "123456";
private static String driverclass= "com.mysql.cj.jdbc.Driver";
private static String connectUrl = "jdbc:mysql://172.19.82.122:3306/xx
获取连接
public static Connection getConnection() {
try {
return DriverManager.getConnection(connectUrl, user, pwd);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
查询
public static void query(Connection conn) {
Statement createStatement = null;
try {
createStatement = conn.createStatement();
ResultSet rs = createStatement.executeQuery(" select * from tb_user");
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
createStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
结果处理
while(rs.next()) {
System.out.println(rs.getString("user_name"));
}