一、最常用的JDBC连接数据库
(参考https://blog.csdn.net/jylsrnzb/article/details/103148354中的三步走)
servlet中连接语句创建init()方法:
Connection dbconn=null;
public void init() {
String dbdriver="com.mysql.cj.jdbc.Driver";
String dburl="jdbc:mysql://localhost:3306/personnel?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=true";
String username="root";
String password="password";
try {
Class.forName(dbdriver);
dbconn=DriverManager.getConnection(dburl,username,password);
}
catch(ClassNotFoundException e1) {
System.out.println(e1);
getServletContext().log("驱动程序类找不到!");
}catch(SQLException e2) {
System.out.println(e2);
}
}
二、数据源建立数据库连接
1.首先在项目的META-INF目录下创建context.xml文件
位置如下:
代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<Context reloadable="true">
<Resource
name="jdbc/webstoreDS"
type="javax.sql.DataSource"
maxActibe="4"
maxIdle="2"
username="root"
password="password"
maxWait="5000"
driverClassName="com.mysql.cj.jdbc.Driver"
url="jdbc:mysql://127.0.0.1:3306/personnel?serverTimezone=UTC"/>
</Context>
3.servlet中修改init()方法,使用数据源对象创建连接
代码如下:
public void init() {
try {
Context context=new InitialContext();
dataSource=(DataSource)context.lookup("java:comp/env/jdbc/webstoreDS");
dbconn=dataSource.getConnection();
}catch(NamingException ne) {
System.out.println("异常"+ne);
}catch(SQLException se) {
System.out.println("异常"+se);
}
}
三、使用C3P0建立数据库连接
1.配置
(1)三个jar包放在lib下
(2)c3p0-config.xml放在src下
结果如下:
c3p0-config.xml的代码如下:
<?xml version="1.0" encoding="utf-8" ?>
<c3p0-config>
<default-config>
<property name="user">root</property>
<property name="password">password</property>
<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
<property name="jdbcUrl">
jdbc:mysql://localhost:3306/personnel?serverTimezone=UTC
</property>
<property name="checkoutTimeout">30000</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</default-config>
<named-config name="hhh">
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">15</property>
<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
<property name="jdbcUrl">
jdbc:mysql://localhost:3306/personnel?serverTimezone=UTC
</property>
<property name="user">root</property>
<property name="password">password</property>
</named-config>
</c3p0-config>
配置完成√
2.常见配置问题
(1)记得jdbcUrl中改成自己的数据库名称,若未连接上且报错中与乱码有关,则一定要在数据库名称后加?serverTimezone=UTC
。
(2)<named-config name="hhh">
双引号中是自己定义的连接名,后续连接需要用到。
3. servlet中修改init()方法
代码如下:
Connection dbconn=null;
DataSource dataSource = null;
//初始化C3P0数据源
public void init() {
try {
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("hhh");
dataSource = comboPooledDataSource;
dbconn=dataSource.getConnection();
}catch(Exception e) {}
四、使用DAO设计模式访问数据库
1.创建Student实体类
(其中包含student的几个属性和getter、setter方法)
2.创建DAO接口
Dao接口是所有接口的根接口,其中定义了默认方法建立到数据库的连接。
代码如下:
import java.sql.*;
import javax.sql.DataSource;
import javax.naming.*;
public interface Dao {
public static DataSource getDataSource() {
DataSource dataSource=null;
try {
Context context=new InitialContext();
dataSource=(DataSource)context.lookup("java:comp/env/jdbc/webstoreDS");
}catch(NamingException ne) {
System.out.println("异常"+ne);
}
return dataSource;
}
public default Connection getConnection() throws SQLException{
DataSource dataSource=getDataSource();
Connection conn=null;
try {
conn=dataSource.getConnection();
}catch(SQLException sqle) {
System.out.println("异常:"+sqle);
}
return conn;
}
}
3.创建DaoException类
DaoException类是一个异常类,当Dao方法运行时异常时抛出。
4.创建StudentDao接口(它继承Dao接口)
代码如下:
import java.sql.SQLException;
import com.domain.Student;
public interface StudentDao extends Dao{
int addStudent(Student student) throws SQLException;
int deleteStudent(String sno) throws SQLException;
}
5.创建StudentDaoImpl类(它实现StudentDao接口)
代码如下:
package com.dao;
import java.sql.*;
import com.domain.Student;
public class StudentDaoImpl implements StudentDao {
public int addStudent(Student student) throws SQLException{
String sql="insert into student values(?,?,?,?,?)";
try {
Connection conn=getConnection();
PreparedStatement pstmt=conn.prepareStatement(sql);
pstmt.setString(1, student.getSno());
pstmt.setString(2, student.getName());
pstmt.setString(3, student.getSex());
pstmt.setInt(4, student.getAge());
pstmt.setString(5, student.getSdept());
int i=pstmt.executeUpdate();
return i;
}catch(SQLException se) {
se.printStackTrace();
return 0;
}
}
public int deleteStudent(String sno) throws SQLException{
String sql="delete from student where sno=?";
try (Connection conn=getConnection();
PreparedStatement pstmt=conn.prepareStatement(sql))
{
pstmt.setString(1, sno);
int i=pstmt.executeUpdate();
return i;
}catch(SQLException se) {
return 0;
}
}
}