1、为项目导入mysql-jdbc包
下载地址:https://how2j.cn/frontdownload?bean.id=224
通常都会把项目用到的jar包统一放在项目的lib目录下
IDEA中打开 File -> Project Structure (Ctrl + Shift + Alt + S),在Libraries 中添加
2、JDBC连接基本流程
初始化驱动->建立数据库连接->创建statement语句->执行SQL语句
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class TestJDBC {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try (
Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8",
"root", "admin");
Statement s = c.createStatement();
)
{
String sql = "insert into hero values(null," + "'提莫'" + "," + 313.0f + "," + 50 + ")";
s.execute(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2、JDBC查询
查询结果放入ResultSet中
注:在取第二列的数据的时候,用的是rs.get(2) ,而不是get(1). 这个是整个Java自带的api里唯二的地方,使用基1的,即2就代表第二个。
String sql3 = "select * from hero";
ResultSet rs = statement.executeQuery(sql3);
System.out.println(rs);
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
float hp = rs.getFloat(3);
int damage = rs.getInt(4);
System.out.printf("%d\t%s\t%f\t%d%n",id,name,hp,damage);
}
3、JDBC插入数据
当需要插入字符串时,sql语句需要拼接,单引号和双引号冗余在一起,可读性很差。
String sql = "insert into hero values(null,"+"'提莫'"+","+313.0f+","+50+")";
因此可以使用PrepareStatement
4、PrepareStatement预编译
和 Statement一样,PreparedStatement也是用来执行sql语句的
与创建Statement不同的是,需要根据sql语句创建PreparedStatement
除此之外,还能够通过设置参数,指定相应的值,而不是Statement那样使用字符串拼接
注: 这是JAVA里唯二的基1的地方,另一个是查询语句中的ResultSet也是基1的。
String sql7 = "insert into hero values(null,?,?,?)";
PreparedStatement ps = connection.prepareStatement(sql7)
ps.setString(1,"盖伦");
ps.setFloat(2,313.0f);
ps.setInt(3,50);
ps.execute();
4、execute与executeUpdate的区别
增删改 | 查询 | 返回值 | |
---|---|---|---|
execute | 支持 | 支持 | 返回boolean类型,true表示执行的是查询语句,false表示执行的是insert,delete,update等等 |
executeUpdate | 支持 | 不支持 | 返回的是int,表示有多少条数据受到了影响 |
5、获取自增id
public static void gerAutoID(){
String sql = "insert into hero values(null,?,?,?)";
try{
Class.forName("com.mysql.jdbc.Driver");
}catch (ClassNotFoundException e){
e.printStackTrace();
}
try(Connection connection = DriverManager.getConnection(url,admin,pass);
PreparedStatement preparedStatement = connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS)
)
{
preparedStatement.setString(1,"亚瑟");
preparedStatement.setFloat(2,616.6f);
preparedStatement.setInt(3,100);
preparedStatement.execute();
ResultSet rs = preparedStatement.getGeneratedKeys();
if(rs.next()){
int id = rs.getInt(1);
System.out.println(id);
}
}catch (SQLException e){
e.printStackTrace();
}
}
6、获取表的元数据
元数据概念:
和数据库服务器相关的数据,比如数据库版本,有哪些表,表有哪些字段,字段类型是什么等等。
public static void getYSJ(){
try{
Class.forName("com.mysql.jdbc.Driver");
}catch (ClassNotFoundException e){
e.printStackTrace();
}
try(Connection connection = DriverManager.getConnection(url,admin,pass))
{
DatabaseMetaData dbmd = connection.getMetaData();
//获取数据库服务器产品名称
System.out.println(dbmd.getDatabaseProductName());
//获取产品版本号
System.out.println(dbmd.getDatabaseMinorVersion());
// 获取数据库服务器用作类别和表名之间的分隔符 如test.user
System.out.println(dbmd.getCatalogSeparator());
//获取驱动版本
System.out.println(dbmd.getDriverVersion());
//获取可用数据库名称
ResultSet rs = dbmd.getCatalogs();
while(rs.next()){
System.out.println("数据库名称\t" + rs.getString(1));
}
}catch (SQLException e){
e.printStackTrace();
}
}
7、JDBC事务
在事务中的多个操作,要么都成功,要么都失败
通过 c.setAutoCommit(false);关闭自动提交
使用 c.commit();进行手动提交
此外,MySQL表中,只有当表的类型是INNODB的时候,才支持事务
修改表的类型为INNODB:
alter table hero ENGINE = innodb;
public static void transaction(){
try{
Class.forName("com.mysql.jdbc.Driver");
}catch (ClassNotFoundException e){
e.printStackTrace();
}
try(
Connection connection = DriverManager.getConnection(url,admin,pass);
Statement statement = connection.createStatement()
){
//有事务的前提下
//在事务中的多个操作,要么都成功,要么都失败
connection.setAutoCommit(false);
String sql1 = "update hero set hp = hp + 1 where id = 2";
statement.execute(sql1);
String sql2 = "updata hero set hp = hp + 1 where id = 3";
statement.execute(sql2);
connection.commit();
}catch (SQLException e){
e.printStackTrace();
}
}
8、JDBC ORM
ORM=Object Relationship Database Mapping (对象和关系数据库的映射)
简单说,一个对象,对应数据库里的一条记录
https://how2j.cn/k/jdbc/jdbc-orm/391.html
9、JDBC DAO
DAO=Data Access Object
数据访问对象
实际上就是运用了练习-ORM中的思路,把数据库相关的操作都封装在这个类里面,其他地方看不到JDBC的代码
public class HeroDAO implements DAO{
public HeroDAO(){
try{
Class.forName("com.mysql.jdbc.Driver");
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}
public Connection getConnection() throws SQLException{
String url = "jdbc:mysql://localhost:3306/how2j?characterEncoding=utf-8";
String admin = "root";
String pass = "root";
return DriverManager.getConnection(url,admin,pass);
}
@Override
public void add(Hero5 hero) {
String sql = "insert into hero values(null,?,?,?)";
try(
Connection connection = getConnection();
PreparedStatement ps = connection.prepareStatement(sql)
){
ps.setString(1,hero.name);
ps.setFloat(2,hero.hp);
ps.setInt(3,hero.damage);
ps.execute();
}catch (SQLException e){
e.printStackTrace();
}
}
@Override
public void delete(int id) {
try (
Connection connection = getConnection();
Statement statement = connection.createStatement()
){
String sql = "delete from hero where id = "+id;
statement.execute(sql);
}catch (SQLException e){
e.printStackTrace();
}
}
@Override
public Hero5 get(int id) {
Hero5 hero = null;
try(
Connection connection = getConnection();
Statement statement = connection.createStatement();
){
String sql = "select * from hero where id = "+id;
ResultSet rs = statement.executeQuery(sql);
if(rs.next()){
hero = new Hero5();
hero.id = id;
hero.name = rs.getString(2);
hero.hp = rs.getFloat("hp");
hero.damage = rs.getInt("damage");
}
}catch (SQLException e){
e.printStackTrace();
}
return hero;
}
@Override
public List<Hero5> list() {
return list(0,Short.MAX_VALUE);
}
@Override
public List<Hero5> list(int start, int count) {
List<Hero5> heros = new ArrayList<>();
String sql = "select * from hero order by id desc limit ?,?";
try(
Connection connection = getConnection();
PreparedStatement ps = connection.prepareStatement(sql)
){
ps.setInt(1,start);
ps.setInt(2,count);
ResultSet rs = ps.executeQuery();
while(rs.next()){
Hero5 hero = new Hero5();
hero.id = rs.getInt("id");
hero.name = rs.getString("name");
hero.hp = rs.getFloat("hp");
hero.damage = rs.getInt("damage");
heros.add(hero);
}
}catch (SQLException e){
e.printStackTrace();
}
return heros;
}
网友评论