public class JDBCdEMO {public static void main(String[] args) throws Exception{//1.注册驱动Class.forName("com.mysql.jdbc.Driver");//2.获取连接String url = "jdbc:mysql://127.0.0.1:3306/test2";String username = "root";String password = "xxxxxx";Connection conn = DriverManager.getConnection(url, username, password);//3.定义sql语句String sql = "update account set money=2000 where id = 1";//4.获取执行对象StatementStatement stmt = conn.createStatement();//5.执行sql,返回值是指影响行数int count = stmt.executeUpdate(sql);//6.处理结果System.out.println(count);//7.释放资源stmt.close();conn.close();}
}
是个工具类,里面大都是静态方法,后续打点获取方法名就可以,注意里面的registerDriver方法
静态代码块中有DriverManager.registerDriver就是DriverManager的方法了
mysql驱动5的jar包,可以省略不写Class.forName,一样能跑,是因为驱动jar包中有
开启事务:setAutoCommit(boolean autoCommit)
提交事务:commit()
回滚事务:rollback()
上代码
public class JDBCDemo2 {public static void main(String[] args) throws Exception{//1.注册驱动Class.forName("com.mysql.jdbc.Driver");//2.获取连接String url = "jdbc:mysql://127.0.0.1:3306/test2";String username = "root";String password = "xxxxxx";Connection conn = DriverManager.getConnection(url, username, password);//3.定义sql语句String sql1 = "update account set money=3000 where id = 1";String sql2 = "update account set money=3000 where id = 2";//4.获取执行对象StatementStatement stmt = conn.createStatement();//使用try,catch来管理事务//5.执行sql,返回值是指影响行数try {//6.开启事务conn.setAutoCommit(false);int count1 = stmt.executeUpdate(sql1);System.out.println(count1);int count2 = stmt.executeUpdate(sql2);System.out.println(count2);//7.提交事务conn.commit();} catch (Exception e) {//8.回滚事务conn.rollback();}//9.释放资源stmt.close();conn.close();}
}
Statement stmt = conn.createStatement();//5.执行sql,返回值是指影响行数int count = stmt.executeUpdate(sql);
if(count>0){System.out.println("修改成功");}else {System.out.println("修改失败");}
代码无变动
封装了DQL查询语句的结果
public class JDBCDemo4 {@Testpublic void testResultSet() throws Exception{//1.注册驱动Class.forName("com.mysql.jdbc.Driver");//2.获取连接String url = "jdbc:mysql://127.0.0.1:3306/test2";String username = "root";String password = "xxxxxx";Connection conn = DriverManager.getConnection(url, username, password);//3.定义sqlString sql = "select * from account";//4.获取statement对象Statement stmt = conn.createStatement();//5.执行sqlResultSet rs = stmt.executeQuery(sql);//6.处理结果,遍历rs中的所有数据//6.1光标向下移动一行,并且判断当前行是否有数据while (rs.next()){//6.2获取数据,可以是列索引,也可以是列名称int id = rs.getInt(1);String name = rs.getString("name");double money = rs.getDouble(3);System.out.println(id);System.out.println(name);System.out.println(money);System.out.println("---------------------");}//7.释放资源rs.close();stmt.close();conn.close();}
}
public class Account {private int id;private String name;private double money;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public double getMoney() {return money;}public void setMoney(double money) {this.money = money;}@Overridepublic String toString() {return "Account{" +"id=" + id +", name='" + name + '\'' +", money=" + money +'}';}
}
@Testpublic void testResultSet2() throws Exception{//1.注册驱动Class.forName("com.mysql.jdbc.Driver");//2.获取连接String url = "jdbc:mysql://127.0.0.1:3306/test2";String username = "root";String password = "xxxxxx";Connection conn = DriverManager.getConnection(url, username, password);//3.定义sqlString sql = "select * from account";//4.获取statement对象Statement stmt = conn.createStatement();//5.执行sqlResultSet rs = stmt.executeQuery(sql);ArrayList list = new ArrayList<>();//6.处理结果,遍历rs中的所有数据//6.1光标向下移动一行,并且判断当前行是否有数据while (rs.next()){Account account = new Account();//6.2获取数据int id = rs.getInt(1);String name = rs.getString("name");double money = rs.getDouble(3);//6.3赋值给对象account.setId(id);account.setName(name);account.setMoney(money);//存入集合list.add(account);}System.out.println(list);//7.释放资源rs.close();stmt.close();conn.close();}
}
@Testpublic void testResultSet2() throws Exception {//2.获取连接String url = "jdbc:mysql://127.0.0.1:3306/test2";String username = "root";String password = "xxxxxx";Connection conn = DriverManager.getConnection(url, username, password);// 接收用户输入 用户名和密码String name = "zhangsan";String pwd = "' or '1' = '1";String sql = "select * from tb_user where username = '" + name + "' and password = '" + pwd + "'";// 获取stmt对象Statement stmt = conn.createStatement();// 执行sqlResultSet rs = stmt.executeQuery(sql);// 判断登录是否成功if (rs.next()) {System.out.println("登录成功~");} else {2.System.out.println("登录失败~");}//7. 释放资源rs.close();stmt.close();conn.close();}
}
@Testpublic void testResultSet2() throws Exception {//2.获取连接String url = "jdbc:mysql://127.0.0.1:3306/test2";String username = "root";String password = "xxxxxx";Connection conn = DriverManager.getConnection(url, username, password);// 接收用户输入 用户名和密码String name = "zhangsan";String pwd = "' or '1' = '1";//定义sqlString sql = "select * from tb_user where username = ? and password = ?";//获取pstmt对象PreparedStatement pstmt = conn.prepareStatement(sql);//设置问号值pstmt.setString(1,name);pstmt.setString(2,pwd);//指定sqlResultSet rs = pstmt.executeQuery();// 判断登录是否成功if (rs.next()) {System.out.println("登录成功~");} else {System.out.println("登录失败~");}//7. 释放资源rs.close();pstmt.close();conn.close();}
}
允许重复使用一个现有的数据库连接,而不是重新新建一个,保证了资源的复用
jar包粘贴到lib后,add as library变成模块有效
代码
/*** Druid数据库连接池演示*/
public class DruidDemo {public static void main(String[] args) throws Exception {//1.导入jar包//2.定义配置文件//3.加载配置文件Properties prop = new Properties();prop.load(new FileInputStream("C:\\Users\\CZyue\\Desktop\\javaSE\\11-JavaWeb补充\\jdbc-demo\\src\\druid.properties"));//4.获取连接池对象DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);//5.获取对应的数据库连接ConnectionConnection connection = dataSource.getConnection();System.out.println(connection);//获取当前路径//System.out.println(System.getProperty("user.dir"));//C:\Users\CZyue\Desktop\javaSE\11-JavaWeb补充\jdbc-demo}
}
JavaEE三层架构:表现层、业务层、持久层
org.mybatis mybatis x.x.x
mysql mysql-connector-java 5.1.46
org.slf4j slf4j-api 1.7.20 ch.qos.logback logback-classic 1.2.3 ch.qos.logback logback-core 1.2.3
7.定义POJP类
public class User {private Integer id;private String username;private String password;private String gender;private String addr;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public String getAddr() {return addr;}public void setAddr(String addr) {this.addr = addr;}@Overridepublic String toString() {return "User{" +"id=" + id +", username='" + username + '\'' +", password='" + password + '\'' +", gender='" + gender + '\'' +", addr='" + addr + '\'' +'}';}
}
public class MybatisDemo {public static void main(String[] args) throws IOException {//1.加载Mybatis的核心配置文件,获取SqlSessionFactoryString resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取SqlSession对象,用它来执行sqlSqlSession sqlSession = sqlSessionFactory.openSession();//3.执行sql语句List users = sqlSession.selectList("test.selectAll");System.out.println(users);//4.释放资源sqlSession.close();}}
与SQL映射文件同名的Mapper接口
这两在一起了
public interface UserMapper {//返回User对象并且是list的集合,根据sql语句判断啦// 方法名和是SQL映射文件中sql语句的idList selectAll();
}
理解:
public static void main(String[] args) throws IOException {//1.加载Mybatis的核心配置文件,获取SqlSessionFactoryString resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取SqlSession对象,用它来执行sqlSqlSession sqlSession = sqlSessionFactory.openSession();//3.原来:执行sql语句//List users = sqlSession.selectList("test.selectAll");//3.1获取UserMapper接口的代理对象//Mapper因为存在同名的配置文件,所以可以找到映射配置文件UserMapper userMapper = sqlSession.getMapper(UserMapper.class);//执行方法//调用方法后selectAll方法后,也是配置文件中的sql语句的id,也就可以获取sql语句了,最后返回ListList users = userMapper.selectAll();System.out.println(users);//4.释放资源sqlSession.close();}
}
有个细节:如果Mapper接口名称和SQL映射文件名称相同,并在同一目录下,则可以使用包扫描的方式简化SQL
mybatis-config.xml中
配置多个数据源
给pojo中的实体类起了别名
在test中创建包和类写
可以将UserMapper和UserMapper.xml匹配起来,跳转方便,以及语法检测
public interface BrandMapper {/*** 查询所有*/public List selectAll();
}
通过BrandMapper类中selectAll()的alt+enter自动生成
public class MyBatisTest {@Testpublic void testSelectAll() throws IOException {//1.加载Mybatis的核心配置文件,获取SqlSessionFactoryString resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取SqlSession对象SqlSession sqlSession = sqlSessionFactory.openSession();//3.获取Mapper接口的代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);//4.执行方法List brands = brandMapper.selectAll();System.out.println(brands);//5.释放资源sqlSession.close();}
}
Brand类中的变量名字和数据中的不同
因此通过起别名的方式保持一致
id, brand_name as brandName, company_name as compangName,ordered, description, status
接收一个id对象,然后返回brand对象
public interface BrandMapper {/*** 查看详情:根据id查询*/Brand selectById(int id);
}
通过BrandMapper类中selectById()的alt+enter自动生成
public class MyBatisTest {@Testpublic void testSelectId() throws IOException {//0.接收参数,现在静态,以后是动态的接收int id = 1;//1.加载Mybatis的核心配置文件,获取SqlSessionFactoryString resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取SqlSession对象SqlSession sqlSession = sqlSessionFactory.openSession();//3.获取Mapper接口的代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);//4.执行方法Brand brand = brandMapper.selectById(id);System.out.println(brand);//5.释放资源sqlSession.close();}
}
List selectByCondition(@Param("status") int status,@Param("companyName") String companyName,@Param("brandName") String brandName);/* List selectByCondition(Brand brand);List selectByCondition(Map map);*/
public class MybatisDemo {public static void main(String[] args) throws IOException {//1.加载Mybatis的核心配置文件,获取SqlSessionFactoryString resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取SqlSession对象,用它来执行sqlSqlSession sqlSession = sqlSessionFactory.openSession();//3.执行sql语句List users = sqlSession.selectList("test.selectAll");System.out.println(users);//4.释放资源sqlSession.close();}}
List selectByCondition(Brand brand);
public class MyBatisTest {@Testpublic void testSelectByCondition() throws IOException {//0.接收参数,现在静态,以后是动态的接收int status = 1;String companyName = "华为";String brandName = "华为";//处理参数companyName = "%" + companyName + "%";brandName = "%" + brandName + "%";//封装对象Brand brand = new Brand();brand.setStatus(status);brand.setCompanyName(companyName);brand.setBrandName(brandName);//1.加载Mybatis的核心配置文件,获取SqlSessionFactoryString resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取SqlSession对象SqlSession sqlSession = sqlSessionFactory.openSession();//3.获取Mapper接口的代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);//4.执行方法//List brands = brandMapper.selectByCondition(status, companyName, brandName);List brands = brandMapper.selectByCondition(brand);System.out.println(brands);//5.释放资源sqlSession.close();}
}
List selectByCondition(Map map);
@Testpublic void testSelectByCondition() throws IOException {//0.接收参数,现在静态,以后是动态的接收int status = 1;String companyName = "华为";String brandName = "华为";//处理参数companyName = "%" + companyName + "%";brandName = "%" + brandName + "%";Map map = new HashMap<>();map.put("status",status);map.put("companyName",companyName);map.put("brandName",brandName);//1.加载Mybatis的核心配置文件,获取SqlSessionFactoryString resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取SqlSession对象SqlSession sqlSession = sqlSessionFactory.openSession();//3.获取Mapper接口的代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);//4.执行方法//List brands = brandMapper.selectByCondition(status, companyName, brandName);//List brands = brandMapper.selectByCondition(brand);List brands = brandMapper.selectByCondition(map);System.out.println(brands);//5.释放资源sqlSession.close();}
}
如果用户只输入了两个,而非三个,进行动态查询,称为动态SQL
增加if判断即可
但是mybatis对于动态SQL有着很大支撑,拥有很多标签进行处理
List selectByCondition(Map map);
public class MyBatisTest {@Testpublic void testSelectByCondition() throws IOException {//0.接收参数,现在静态,以后是动态的接收int status = 1;String companyName = "华为";String brandName = "华为";//处理参数companyName = "%" + companyName + "%";brandName = "%" + brandName + "%";//封装对象
// Brand brand = new Brand();
// brand.setStatus(status);
// brand.setCompanyName(companyName);
// brand.setBrandName(brandName);Map map = new HashMap<>();//map.put("status",status);map.put("companyName",companyName);map.put("brandName",brandName);//1.加载Mybatis的核心配置文件,获取SqlSessionFactoryString resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取SqlSession对象SqlSession sqlSession = sqlSessionFactory.openSession();//3.获取Mapper接口的代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);//4.执行方法//List brands = brandMapper.selectByCondition(status, companyName, brandName);//List brands = brandMapper.selectByCondition(brand);List brands = brandMapper.selectByCondition(map);System.out.println(brands);//5.释放资源sqlSession.close();}
}
使用mybatis中的choose(when,otherwise),类比java的swith,case,default
List selectByConditionSingle(Brand brand);
@Testpublic void testSelectByCondition() throws IOException {//0.接收参数,现在静态,以后是动态的接收int status = 1;String companyName = "华为";String brandName = "华为";//处理参数companyName = "%" + companyName + "%";brandName = "%" + brandName + "%";//封装对象Brand brand = new Brand();brand.setStatus(status);//brand.setCompanyName(companyName);//brand.setBrandName(brandName);//1.加载Mybatis的核心配置文件,获取SqlSessionFactoryString resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取SqlSession对象SqlSession sqlSession = sqlSessionFactory.openSession();//3.获取Mapper接口的代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);//4.执行方法//List brands = brandMapper.selectByCondition(status, companyName, brandName);//List brands = brandMapper.selectByCondition(brand);List brands = brandMapper.selectByConditionSingle(brand);System.out.println(brands);//5.释放资源sqlSession.close();}
}
或者标签
void add(Brand brand);
insert into tb_brand(brand_name, company_name, ordered, description, status)values (#{brand_name},#{companyname},#{ordered},#{description},#{status});
@Testpublic void testAdd() throws IOException {//0.接收参数,现在静态,以后是动态的接收int status = 1;String companyName = "波导手机";String brandName = "波导";String description = "手机中的战斗机";int ordered = 100;//封装对象Brand brand = new Brand();brand.setStatus(status);brand.setCompanyName(companyName);brand.setBrandName(brandName);brand.setDescription(description);brand.setOrdered(ordered);//1.加载Mybatis的核心配置文件,获取SqlSessionFactoryString resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取SqlSession对象SqlSession sqlSession = sqlSessionFactory.openSession();//3.获取Mapper接口的代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);//4.执行方法brandMapper.add(brand);//5.释放资源sqlSession.close();}
因此需要手动提交,增加这一行
//5.提交事务//sqlSession.commit();
//2.获取SqlSession对象SqlSession sqlSession = sqlSessionFactory.openSession(true);
希望有时候可以返回主键的值,即id的值
可以在xml中配置useGeneratedKeys=“true” keyProperty=“id”
insert into tb_brand(brand_name, company_name, ordered, description, status)values (#{brandName},#{companyName},#{ordered},#{description},#{status});
brandMapper.add(brand);Integer id = brand.getId();System.out.println(id);
int update(Brand brand);
update tb_brandsetbrand_name = #{brandName},company_name = #{companyName},ordered =#{ordered},description = #{description},status = #{status}where id =#{id};
@Testpublic void testAdd() throws IOException {//0.接收参数,现在静态,以后是动态的接收int status = 1;String companyName = "波导手机";String brandName = "波导";String description = "波导手机手机中的战斗机";int ordered = 200;int id = 5;//封装对象Brand brand = new Brand();brand.setStatus(status);brand.setCompanyName(companyName);brand.setBrandName(brandName);brand.setDescription(description);brand.setOrdered(ordered);brand.setId(id);//1.加载Mybatis的核心配置文件,获取SqlSessionFactoryString resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取SqlSession对象SqlSession sqlSession = sqlSessionFactory.openSession(true);//3.获取Mapper接口的代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);//4.执行方法int count = brandMapper.update(brand);System.out.println(count);//5.提交事务//sqlSession.commit();//6.释放资源sqlSession.close();}
}
如果传进来两个值,其他的字段没值会被修改成null
update tb_brandbrand_name = #{brandName}, company_name = #{companyName}, ordered =#{ordered}, description = #{description}, status = #{status} where id =#{id};
@Testpublic void testAdd() throws IOException {//0.接收参数,现在静态,以后是动态的接收int status = 0;String companyName = "波导手机";String brandName = "波导";String description = "波导手机手机中的战斗机";int ordered = 200;int id = 5;//封装对象Brand brand = new Brand();brand.setStatus(status);//brand.setCompanyName(companyName);//brand.setBrandName(brandName);//brand.setDescription(description);//brand.setOrdered(ordered);brand.setId(id);//1.加载Mybatis的核心配置文件,获取SqlSessionFactoryString resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取SqlSession对象SqlSession sqlSession = sqlSessionFactory.openSession(true);//3.获取Mapper接口的代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);//4.执行方法//List brands = brandMapper.selectByCondition(status, companyName, brandName);//List brands = brandMapper.selectByCondition(brand);//List brands = brandMapper.selectByConditionSingle(brand);int count = brandMapper.update(brand);System.out.println(count);//5.提交事务//sqlSession.commit();//6.释放资源sqlSession.close();}
}
/*** 根据id删除*/void deleteById(int id);
delete from tb_brand where id = #{id};
@Testpublic void testDeleteById() throws IOException {//0.接收参数,现在静态,以后是动态的接收int id = 6;//1.加载Mybatis的核心配置文件,获取SqlSessionFactoryString resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取SqlSession对象SqlSession sqlSession = sqlSessionFactory.openSession(true);//3.获取Mapper接口的代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);//4.执行方法brandMapper.deleteById(id);//5.提交事务//sqlSession.commit();//6.释放资源sqlSession.close();}
批量删除这个数据
/*** 批量删除*/void deleteByIds(@Param("ids") int[] ids);
delete from tb_brand where id in(#{id} );
@Testpublic void testDeleteByIds() throws IOException {//0.接收参数,现在静态,以后是动态的接收int[] ids = {5,7};//1.加载Mybatis的核心配置文件,获取SqlSessionFactoryString resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取SqlSession对象SqlSession sqlSession = sqlSessionFactory.openSession(true);//3.获取Mapper接口的代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);//4.执行方法brandMapper.deleteByIds(ids);//5.提交事务//sqlSession.commit();//6.释放资源sqlSession.close();}
或者
void deleteByIds( int[] ids);
" item=“id” separator=“,”>2.6 参数传递
User select(@Param("username") String username, @Param("password") String password);
//4.执行方法String username = "zhangsan";String password = "123";userMapper.select(username,password);
2.7 注解完成增删改查
User selectById(int id);
@Select("select * from tb_user where id = #{id}")User selectById(int id);
@Testpublic void testSelectById() throws IOException {//1.加载Mybatis的核心配置文件,获取SqlSessionFactoryString resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//2.获取SqlSession对象SqlSession sqlSession = sqlSessionFactory.openSession(true);//3.获取Mapper接口的代理对象UserMapper userMapper = sqlSession.getMapper(UserMapper.class);//4.执行方法User user = userMapper.selectById(1);System.out.println(user);//5.提交事务//6.释放资源sqlSession.close();}
}