- 加载数据库驱动包
Class.forName("com.mysql.jdbc.Driver");
- 创建数据库连接对象:Connection
Connection root = DriverManager.getConnection("jdbc:mysql://localhost:3306/myschool?useUnicode=true&characterEncoding=utf8", "root", "123456");
例:Class.forName("com.mysql.jdbc.Driver");
例:Connection root = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名字", "数据库用户名", "密码");
localhost:主机 3306:端口号
如果出现乱码情况:?useUnicode=true&characterEncoding=utf8
- 通过数据库连接对象,创建出装载mysql语句的容器
Statement statement = root.createStatement();
例:Statement statement = root.createStatement();
- 创建mysql语句,用于接下来的数据库操作
String sql ="select *from result "; result为表名
- 拿到返回的结果做进一步操作
//查询 UserInfo:类名
public static List<UserInfo> cha(){
String sql1 ="select *from 表名 ";
List<UserInfo> cha = JdbcUitl02.cha(sql1, null);
return cha; //返回的是一个集合 所以需要循环遍历
}
List<UserInfo> cha = cha();
for (UserInfo aa :cha){
//高级for循环
System.out.println(aa);
}
- 关闭连接对象:先开启的后关闭
//关闭
public static void guan(Connection root, PreparedStatement ptm, ResultSet rs){
if (root!=null){
try {
root.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (ptm!=null){
try {
ptm.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (rs !=null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}