步骤:
导入jar包
第一步:加载mysql驱动 (反射机制,推荐使用动态加载)
第二步:进行数据库连接
第三步:建立查询语句
第四步:执行sql语句
第五步:按行读取数据
第六步:关闭资源
Statement 和PreparedStatement 的区别?https://www.jianshu.com/p/de20f340dc89
PreparedStatement 继承 Statement
代码
package com.sln;
import java.sql.*;
import java.util.*;
import java.util.Date;
/**
* Created by Administrator on 2019/7/20
*/
public class JDBC {
public static void main(String[] args) {
//jdbc连接数据库
Connection connection = null;
PreparedStatement ps = null;
ResultSet resultSet = null;
try {
//第一步,加载mysql驱动.Class.forName() 用来加载某个类的
Class.forName("com.mysql.jdbc.Driver");
//第二步,进行数据库连接 一般
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?" +
"useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull", "用户名", "密码");
//第三步,创建statement 建立sql语句的查询
//createStatement 执行sql语句的时候不能加参数只能select * from 表名
// Statement statement = connection.createStatement();
ps = connection.prepareStatement("SELECT * from student");
//第四步,执行sql语句,返回resultset结果集
resultSet = ps.executeQuery();
// Map<String,Object> mapTest = new HashMap<>();
List<Map<String,Object>> mapStudentlist = new ArrayList<>();
//第五步
while (resultSet.next()) {
int id = resultSet.getInt("sid");
String name = resultSet.getString("sname");
Date birth = resultSet.getDate("birth");
Map<String,Object> mapStudent = new HashMap<>();
mapStudent.put("sid",id);
mapStudent.put("name",name);
mapStudent.put("birth",birth);
mapStudentlist.add(mapStudent);
System.out.println(String.format("数据student表--id:%s,name:%s", id, name));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭对象
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}