public class DBUtil {
public static void main(String[] args) {
String url = "jdbc:mysql://127.0.0.1:3306/test"; //数据库url
String userName = "root"; //数据库用户名
String password = "123456"; //数据库密码
Connection connection = null;
Statement statement = null;
try {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接
connection = DriverManager.getConnection(url, userName, password);
//3.创建statement语句
statement = connection.createStatement();
//4.执行查询
String sqlGirlInfo = "select * from girlinfo";
ResultSet rs = statement.executeQuery(sqlGirlInfo);
//5.对执行结果进行处理
while(rs.next()){
System.out.println(rs.getString("user_name") + "-" +rs.getInt("age"));
}
}catch (Exception e){
}finally {
//6.最终关闭资源
try {
if(connection!=null){
connection.close();
}
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
在此之前,需要引入mysql-connector-java包