java專案中資料庫的連線(使用mybatis和不使用)
(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:"+username);
try {
String sql="select * from users where username='"+username+"'";
pStat =conn.prepareStatement(sql);
rs=pStat.executeQuery();
if( rs.next() ) return true;
else { System.out.println("rs不為空"); return false;}
}catch (Exception e) { System.out.println("異常"); return false; }
finally{ close(); }
}
使用mybatis框架訪問資料庫(資料庫配置檔案)
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/testdb" />
<property name="username" value="root" />
<property name="password" value="lfy1224" />
</dataSource>
</environment>
</environments>
<mappers>
<!-- 註冊userMapper.xml檔案 -->
<mapper resource="mapper/userMapper.xml"/>
<!-- 註冊IUserMapper對映介面 -->
<mapper class="mapper.IUserMapper" />
</mappers>
</configuration>
第一種:比較簡單
//mybatis實現增查刪改的第一種方法,基於註解的實現
public interface IUserMapper {
@Insert("insert into users(username,password) values(#{username},#{password})")
public int addUser(User user);
@Delete("delete from users where id=#{id}")
public int deleteUser(int id);
@Update("update users set username=#{username},password=#{password} where id=#{id}")
public int updateUser(User user);
@Select("select * from users where id=#{id}")
public User getUserById(int id);
@Select("select * from users")
public List<User> getAllUsers();
}
使用示例:
String resource="mybatis/mybatis-config.xml";
InputStream inputStream=Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession=sqlSessionFactory.openSession();
IUserMapper mapper=sqlSession.getMapper(IUserMapper.class);
User user=new User();
user.setUsername("liufangyuan");
user.setPassword("lfy1224");
int add=mapper.addUser(user);
sqlSession.commit();
sqlSession.close();
//第二種基於配置檔案的增查刪改
userMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mapper.userMapper">
<!--查詢一個使用者資訊-->
<!-- 獲得使用者id,憑藉id來查詢其他的資訊 -->
<!-- resuleType屬性決定了查詢的資料與User表裡的資料一一對應 -->
<select id="getUser" resultType="entity.User" parameterType="int">
select * from users where id= #{id}
</select>
<!--刪除一個使用者-->
<!--parameterType指的是將要接受的資料的型別 -->
<delete id="deleteUser" parameterType="int">
delete * from users where id=#{id}
</delete>
<!--建立使用者 -->
<insert id="addUser" parameterType="entity.User">
insert into users(username,password) values(#{username},#{password})
</insert>
<!--查詢全部使用者-->
<select id="getAllUsers" resultType="entity.User">
select * from users
</select>
<!--修改使用者-->
<update id="updateUser" parameterType="entity.User">
update users set username=#{username},password=#{password} where id=#{id}
</update>
</mapper>
CRUD的一個例項
public void testAdd() throws IOException {
String resource = "mybatis/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
String statement = "mapper.userMapper.addUser";
User user = new User();
user.setUsername("yy");
user.setPassword("xx");
int retResult = sqlSession.insert(statement, user);
sqlSession.commit();
sqlSession.close();
}
使用spring之後好像就沒有構造資料庫連線connection這一步驟了