java项目中数据库的连接(使用mybatis和不使用)

这篇博客对比了在Java项目中使用MyBatis框架与不使用框架连接数据库的方法。非MyBatis方式涉及数据库连接的创建、关闭,而MyBatis通过配置文件和映射接口简化了数据库操作。文中详细展示了MyBatis的注解和XML配置文件的使用示例,以及如何进行CRUD操作。
摘要由CSDN通过智能技术生成

(eclipse环境)首先介绍一下不使用mybatis框架(应该不会不知道的)来连接数据库

先要写出数据库的基本信息,建立数据库连接connection,声明切断连接的close()函数,

        public static final String DRIVER="com.mysql.jdbc.Driver";
public static final String DBURL="jdbc:mysql://localhost:3306/testdb";
public static final String DBUSER="root";
public static final String DBPASS="lfy1224";
private Connection conn=null;
private PreparedStatement pStat=null;
private ResultSet rs=null;

public void close(){
        try{
if( rs!=null ) rs.close();
if( pStat!=null ) pStat.close();
if( conn!=null ) conn.close();
        }catch(Exception e){ e.printStackTrace();        }
     }  //end close

public Connection getConnectionn1(){

       try{

                 //加载驱动

Class.forName(DRIVER).newInstance(); 

                 //返回连接

    return DriverManager.getConnection(DBURL,DBUSER,DBPASS);
       }catch(Exception e){
return null;
       }
   }
//是否存在存在返回true(一个使用的例子)
public boolean isUsernameExists(String username) {
       conn=getConnectionn1();
       System.out.println("username:"

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Mybatis连接数据库的步骤如下: 1. 添加MybatisMybatis-Spring的依赖 ```xml <!-- Mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> ``` 2. 配置数据源 在`application.properties`配置数据源的属性,例如: ```properties spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=password spring.datasource.driver-class-name=com.mysql.jdbc.Driver ``` 3. 创建Mapper接口和SQL语句 Mapper接口是指定SQL语句的接口。可以使用注解或XML来指定SQL语句。 例如,创建一个UserMapper接口和XML文件: UserMapper.java ```java @Mapper public interface UserMapper { @Select("SELECT * FROM user WHERE id = #{id}") User findById(long id); } ``` UserMapper.xml ```xml <mapper namespace="com.example.mapper.UserMapper"> <select id="findById" resultType="com.example.model.User"> SELECT * FROM user WHERE id = #{id} </select> </mapper> ``` 4. 注册Mapper接口 在启动类添加`@MapperScan`注解,指定Mapper接口所在的包: ```java @SpringBootApplication @MapperScan("com.example.mapper") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 5. 使用Mapper接口进行数据操作 在需要使用Mapper接口的地方注入即可,例如: ```java @Service public class UserService { @Autowired private UserMapper userMapper; public User findById(long id) { return userMapper.findById(id); } } ``` 以上就是在Spring Boot使用Mybatis连接数据库的步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值