一、导入connection的jar包
jar包地址:https://pan.baidu.com/s/1L061j1ZisX-ilmc_p21vwA
二、编写代码
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
// 1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
// 2.获得连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mytest", "root", "000000");
// 3.创建sql语句
String sql = "SELECT * FROM test";
// 4.传递sql语句
pstmt = conn.prepareStatement(sql);
// 5.获得结果集
rs = pstmt.executeQuery();
// 6.打印结果集
while (rs.next()) {
String name = rs.getString(1);
System.out.println(name);
}
} catch (ClassNotFoundException e) {
System.out.println("连接失败");
} catch (SQLException e) {
System.out.println("连接失败");
} finally {
//7.首先判断驱动是否为空,然后关闭所有驱动
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}