1、在IDEA里创建Maven项目
1.1、点击Create New Project
2、用Maven连接Mysql的JDBC驱动
2.1、打开src下的pom.xml文件, 在里面添加Mysql的jdbc包的引用,代码如下
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
</dependencies>
2.2、添加完成后,IDEA右下角会出现下图提示,点击提示中的Import Changes,Maven就会开始下载资源
2.3、下载时页面左下角出现正在下载的提示
2.4、下载完成变成绿勾
3、连接数据库第一种方式:直接注册驱动,向数据库插入数据(不推荐使用)
3.1、在src——main——java目录下,新建一个LinkDatabaseInsert的类
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException; public class LinkDatabaseInsert {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1.注册数据库的驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取数据库连接(里面内容依次是:"jdbc:mysql://主机名:端口号/数据库名","用户名","登录密码")
Connection connection = DriverManager.getConnection("jdbc:mysql://rm-uf6lgkv4fd9776rxego.mysql.rds.aliyuncs.com:3306/study","root","whmilyY123!");
//3.需要执行的sql语句(?是占位符,代表一个参数)
String sql = "insert into stu(id,name,age) values(?,?,?)";
//4.获取预处理对象,并依次给参数赋值
PreparedStatement statement = connection.prepareCall(sql);
statement.setInt(1,12); //数据库字段类型是int,就是setInt;1代表第一个参数
statement.setString(2,"小明"); //数据库字段类型是String,就是setString;2代表第二个参数
statement.setInt(3,16); //数据库字段类型是int,就是setInt;3代表第三个参数
//5.执行sql语句(执行了几条记录,就返回几)
int i = statement.executeUpdate();
System.out.println(i);
//6.关闭jdbc连接
statement.close();
connection.close();
}
}
3.2、运行程序,返回1,说明插入成功
4、连接数据库第二种方式——新建数据库配置文件,获取配置文件信息后,再注册数据库驱动
4.1、利用反射获取新建的数据库配置文件db.properties里的信息
4.1.1、在src——main——resources目录下,新建db.properties文件
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://rm-uf6lg6rxego.mysql.rds.aliyuncs.com:3306/study
user=root
password=wY123!
4.1.2、新建util包,然后在里面创建JdbcUtil类,利用反射获取db.properties文件信息,最后返回数据库连接
package util; import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties; //获取到db.properties文件中的数据库信息
public class JdbcUtil {
//私有变量
private static String driver;
private static String url;
private static String user;
private static String password; //静态块
static{
try{
//1.新建属性集对象
Properties properties = new Properties();
//2通过反射,新建字符输入流,读取db.properties文件
InputStream input = JdbcUtil.class.getClassLoader().getResourceAsStream("db.properties");
//3.将输入流中读取到的属性,加载到properties属性集对象中
properties.load(input);
//4.根据键,获取properties中对应的值
driver = properties.getProperty("driver");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
}catch(Exception e){
e.printStackTrace();
}
} //返回数据库连接
public static Connection getConnection(){
try{
//注册数据库的驱动
Class.forName(driver);
//获取数据库连接(里面内容依次是:主机名和端口、用户名、密码)
Connection connection = DriverManager.getConnection(url,user,password);
//返回数据库连接
return connection;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
4.1.3、在java目录下创建LinkMysql类,调用JdbcUtil类返回的数据库连接操作数据库
import util.JdbcUtil; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException; public class LinkMysql {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//获取数据库连接
Connection connection = JdbcUtil.getConnection();
//需要执行的sql语句
String sql = "insert into stu(id,name,age) values(?,?,?)";
//获取预处理对象,并给参数赋值
PreparedStatement statement = connection.prepareCall(sql);
statement.setInt(1,14);
statement.setString(2,"李四");
statement.setInt(3,16);
//执行sql语句(插入了几条记录,就返回几)
int i = statement.executeUpdate(); //executeUpdate:执行并更新
System.out.println(i);
//关闭jdbc连接
statement.close();
connection.close();
}
}
4.2、通过ResourceBundle类获取新建的数据库配置文件db.properties里的信息
4.2.1、在util包里面创建创建JdbcUtil2类,ResourceBundle类获取db.properties文件信息,最后返回数据库连接
package util; import java.sql.*;
import java.util.ResourceBundle; public class JdbcUtil2 {
//私有变量
private static String driver;
private static String url;
private static String user;
private static String password; //静态块
static{
try{
//2.3通过ResourceBundle类拿到数据库连接信息
ResourceBundle resourceBundle = ResourceBundle.getBundle("db");
driver = resourceBundle.getString("driver");
url = resourceBundle.getString("url");
user = resourceBundle.getString("user");
password = resourceBundle.getString("password");
}catch(Exception e){
e.printStackTrace();
}
} //返回数据库连接
public static Connection getConnection(){
try{
//注册数据库的驱动
Class.forName(driver);
//获取数据库连接(里面内容依次是:主机名和端口、用户名、密码)
Connection connection = DriverManager.getConnection(url,user,password);
//返回数据库连接
return connection;
}catch (Exception e){
e.printStackTrace();
}
return null;
} //关闭结果集
public static void closeResultSet(ResultSet resultSet) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} //关闭预处理对象
public static void closeStatement(Statement statement) {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} //关闭数据库连接
public static void closeConnection(Connection connection){
if(connection != null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} //一次性关闭上面三个
public static void closeResource(ResultSet resultSet,Statement statement,Connection connection){
closeResultSet(resultSet);
closeStatement(statement);
closeConnection(connection);
}
}
4.2.2、在java目录下创建LinkMysql2类,调用JdbcUtil2类返回的数据库连接操作数据库
import util.JdbcUtil2; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException; public class LinkMysql2 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//获取数据库连接
Connection connection = JdbcUtil2.getConnection();
//需要执行的sql语句
String sql = "insert into stu(id,name,age) values(?,?,?)";
//获取预处理对象,并给参数赋值
PreparedStatement statement = connection.prepareCall(sql);
statement.setInt(1,19);
statement.setString(2,"王五");
statement.setInt(3,16);
//执行sql语句(执行了几条记录,就返回几)
int i = statement.executeUpdate(); //executeUpdate:执行并更新
System.out.println(i);
//关闭jdbc连接
JdbcUtil2.closeResource(null,statement,connection);
}
}
import util.JdbcUtil2; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException; public class LinkMysql2 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//获取数据库连接
Connection connection = JdbcUtil2.getConnection();
//需要执行的sql语句
String sql = "insert into stu(id,name,age) values(?,?,?)";
//获取预处理对象,并给参数赋值
PreparedStatement statement = connection.prepareCall(sql);
statement.setInt(1,19);
statement.setString(2,"王五");
statement.setInt(3,16);
//执行sql语句(执行了几条记录,就返回几)
int i = statement.executeUpdate(); //executeUpdate:执行并更新
System.out.println(i);
//关闭jdbc连接
JdbcUtil2.closeResource(null,statement,connection);
}
}
5、连接数据库的第三种方式:新建数据库配置文件,获取配置文件信息后,再通过DButils工具包连接数据库
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.5</version>
</dependency>
import org.apache.commons.dbutils.QueryRunner;
import util.JdbcUtil2; import java.sql.Connection;
import java.sql.SQLException; public class DbutilsInsert {
public static void main(String[] args) throws SQLException {
//创建dbUtils里面的QueryRunner对象
QueryRunner queryRunner = new QueryRunner();
//sql语句
String sql = "insert into stu(id,name,age) values(?,?,?)";
//存参数值的数组
Object[] objects = {20,"小红",11};
//获取数据库连接
Connection connection = JdbcUtil2.getConnection();
//执行sql语句,并返回影响的行数
int i = queryRunner.update(connection,sql,objects);
System.out.println(i);
//关闭数据库连接
connection.close();
}
}
import org.apache.commons.dbutils.QueryRunner;
import util.JdbcUtil2; import java.sql.Connection;
import java.sql.SQLException; public class DbutilsUpdate {
public static void main(String[] args) throws SQLException {
//创建dbUtils里面的QueryRunner对象
QueryRunner queryRunner = new QueryRunner();
//sql语句
String sql = "update stu set name=? where id=?";
//存参数值的数组
Object[] objects = {"红红",21};
//获取数据库连接
Connection connection = JdbcUtil2.getConnection();
//执行sql语句,并返回影响的行数
int i = queryRunner.update(connection,sql,objects);
System.out.println(i);
//关闭数据库连接
connection.close();
}
}
import org.apache.commons.dbutils.QueryRunner;
import util.JdbcUtil2; import java.sql.Connection;
import java.sql.SQLException; public class DbutilsDelete {
public static void main(String[] args) throws SQLException {
//创建dbUtils里面的QueryRunner对象
QueryRunner queryRunner = new QueryRunner();
//sql语句
String sql = "delete from stu where id=?";
//存参数值的数组
Object[] objects = {11};
//获取数据库连接
Connection connection = JdbcUtil2.getConnection();
//执行sql语句,并返回影响的行数
int i = queryRunner.update(connection,sql,objects);
System.out.println(i);
//关闭数据库连接
connection.close();
}
}
5.5、创建UtilsSelectArrayHandler类,查询数据(ArrayHandler()只会返回第一条记录)
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import util.JdbcUtil2; import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays; public class UtilsSelectArrayHandler {
public static void main(String[] args) throws SQLException {
//创建dbUtils里面的QueryRunner对象
QueryRunner queryRunner = new QueryRunner();
//sql语句
String sql = "select * from stu where age>?";
//获取数据库连接
Connection connection = JdbcUtil2.getConnection();
//存参数值的数组
Object[] params = {16};
//执行查询,并以数组的形式返回查询结果(new ArrayHandler()只会返回第一条记录)
Object[] objects = queryRunner.query(connection,sql, new ArrayHandler(),params);
System.out.println(Arrays.toString(objects));
System.out.println("\n");
//关闭数据库连接
connection.close();
}
}
5.6、创建UtilsSelectArrayListHandler类,查询数据(ArrayListHandler()会返回所有查询到的记录)
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import util.JdbcUtil2; import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List; public class UtilsSelectArrayListHandler {
public static void main(String[] args) throws SQLException {
//创建dbUtils里面的QueryRunner对象
QueryRunner queryRunner = new QueryRunner();
//sql语句
String sql = "select * from stu where age>?";
//获取数据库连接
Connection connection = JdbcUtil2.getConnection();
//存参数值的数组
Object[] params = {16};
//执行查询,并以数组的形式返回查询结果(new ArrayListHandler()返回所有查询到的记录)
List<Object[]> lists = queryRunner.query(connection,sql, new ArrayListHandler(),params);
for(Object[] item:lists){
System.out.println(Arrays.toString(item));
}
//关闭数据库连接
connection.close();
}
}
先创建student类
public class Student {
private String id;
private String name;
private int age;
private String tname; public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String getTname() {
return tname;
} public void setTname(String tname) {
this.tname = tname;
} @Override
public String toString() {
return "Student{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", age=" + age +
", tname='" + tname + '\'' +
'}';
}
}
再创建UtilsSelectBeanHandler类
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import util.JdbcUtil2; import java.sql.Connection;
import java.sql.SQLException; public class UtilsSelectBeanHandler {
public static void main(String[] args) throws SQLException {
//创建dbUtils里面的QueryRunner对象
QueryRunner queryRunner = new QueryRunner();
//sql语句
String sql = "select * from stu where age>?";
//获取数据库连接
Connection connection = JdbcUtil2.getConnection();
//存参数值的数组
Object[] params = {16};
//执行查询,并以数组的形式返回查询结果(new BeanHandler()只会返回第一条记录,并转成对象)
Student student = queryRunner.query(connection,sql, new BeanHandler<Student>(Student.class),params);
System.out.println(student);
System.out.println("\n");
//关闭数据库连接
connection.close();
}
}
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import util.JdbcUtil2; import java.sql.Connection;
import java.sql.SQLException;
import java.util.List; public class UtilsSelectBeanListHandler {
public static void main(String[] args) throws SQLException {
//创建dbUtils里面的QueryRunner对象
QueryRunner queryRunner = new QueryRunner();
//sql语句
String sql = "select * from stu where age>?";
//获取数据库连接
Connection connection = JdbcUtil2.getConnection();
//存参数值的数组
Object[] params = {16};
//执行查询,并以数组的形式返回查询结果(new BeanListHandler()返回查询到的所有记录,并转成对象)
List<Student> students = queryRunner.query(connection,sql, new BeanListHandler<Student>(Student.class),params);
System.out.println(students);
//关闭数据库连接
connection.close();
}
}
5.9、创建UtilsSelectColumnListHandler类,查询数据(ColumnListHandler会返回结果中指定的列)
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import util.JdbcUtil2; import java.sql.Connection;
import java.sql.SQLException;
import java.util.List; public class UtilsSelectColumnListHandler {
public static void main(String[] args) throws SQLException {
//创建dbUtils里面的QueryRunner对象
QueryRunner queryRunner = new QueryRunner();
//sql语句
String sql = "select * from stu where age>?";
//获取数据库连接
Connection connection = JdbcUtil2.getConnection();
//存参数值的数组
Object[] params = {16};
//执行查询,并以数组的形式返回查询结果(new ColumnListHandler<>()返回结果中指定的列)
List<Object> strs = queryRunner.query(connection,sql, new ColumnListHandler<>("name"),params);
System.out.println(strs);
for(Object item:strs){
System.out.println(item);
}
//关闭数据库连接
connection.close();
}
}
5.10、创建UtilsSelectScalarHandler类,查询单数据(ScalarHandler返回分组函数的值)
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import util.JdbcUtil2; import java.sql.Connection;
import java.sql.SQLException; public class UtilsSelectScalarHandler {
public static void main(String[] args) throws SQLException {
//创建dbUtils里面的QueryRunner对象
QueryRunner queryRunner = new QueryRunner();
//sql语句
String sql = "select max(age) from stu";
//获取数据库连接
Connection connection = JdbcUtil2.getConnection();
//存参数值的数组
Object[] params = {};
//执行查询,并以数组的形式返回查询结果(new ScalarHandler<>()返回分组函数的值)
int age = queryRunner.query(connection,sql, new ScalarHandler<>(),params);
System.out.println(age);
//关闭数据库连接
connection.close();
}
}
6、用c3p0连接池,连接数据库
6.1、在scr——pom.xml文件里,引入c3p0包
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
6.2、在src——main——resources下增加c3p0-config.mxl文件
<?xml version="1.0" encoding="UTF-8"?> <c3p0-config>
<default-config>
<!-- 配置数据库驱动 -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<!-- 配置数据库链接地址 -->
<property name="jdbcUrl">jdbc:mysql://rm-uf9776rxego.mysql.rds.aliyuncs.com:3306/study</property>
<!-- 配置数据库用户名 -->
<property name="user">root</property>
<!-- 配置数据库密码 -->
<property name="password">whmilyY123!</property> <!-- 扩展配置 -->
<!-- 获取连接超时设置,默认是一直等待,单位毫秒 -->
<property name="checkoutTimeout">30000</property>
<!--每多少秒检查所有连接池中的空闲连接。Default: 0 -->
<property name="idleConnectionTestPeriod">30</property>
<!-- 初始化连接池的连接数 -->
<property name="initialPoolSize">10</property>
<!--最大空闲时间,多少秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
<property name="maxIdleTime">30</property>
<!--连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize">100</property>
<!-- 连接池中保留的最小连接数 -->
<property name="minPoolSize">10</property>
<!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default:0 -->
<property name="maxStatements">200</property>
<!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0 -->
<property name="maxStatementsPerConnection">200</property>
<!--c3p0是异步操作的,缓慢的JDBC操作通过帮助进程完成。扩展这些操作可以有效的提升性能 通过多线程实现多个操作同时被执行。Default:3 -->
<property name="numHelperThreads">3</property>
</default-config>
</c3p0-config>
6.3、在src——main——java——util里添加DataSourceUtils类
package util; import com.mchange.v2.c3p0.ComboPooledDataSource; import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; public class DataSourceUtils {
private static ComboPooledDataSource ds = new ComboPooledDataSource(); /**
* 获取数据源
*
* @return 连接池
*/
public static DataSource getDataSource() {
return ds;
} /**
* 释放资源
*
* @param conn
* @param st
* @param rs
*/
public static void CloseResource(Connection conn, Statement st, ResultSet rs) {
closeResultSet(rs);
closeStaement(st);
closeConn(conn);
} /**
* 获取连接
*
* @return 连接
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
return ds.getConnection();
} /**
* 释放连接
*
* @param conn 连接
*/
public static void closeConn(Connection conn) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
conn = null;
}
}
} /**
* 释放语句执行者
*
* @param st 语句执行者
*/
public static void closeStaement(Statement st) {
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
st = null;
}
}
} /**
* 释放结果集
*
* @param rs 结果集
*/
public static void closeResultSet(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
rs = null;
}
}
}
}
6.4、新建C3p0Select类,用数据库连接池的方式查询
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import util.DataSourceUtils; import java.sql.SQLException;
import java.util.List; public class C3p0Select {
public static void main(String[] args) throws SQLException {
//创建dbUtils里面的QueryRunner对象,并获取数据库连接
QueryRunner queryRunner = new QueryRunner(DataSourceUtils.getDataSource());
//sql语句
String sql = "select * from stu where age>?";
//存参数值的数组
Object[] params = {16};
//执行查询,并以数组的形式返回查询结果(new BeanListHandler()返回查询到的所有记录,并转成对象)
List<Student> students = queryRunner.query(sql, new BeanListHandler<Student>(Student.class),params);
System.out.println(students);
}
}