首先创建工程,导入jar包
1.注册驱动
//注册驱动
//利用反射,较为灵活
Class.forName("com.mysql.cj.jdbc.Driver");
/**问题:会注册俩次驱动
* 解决方案:只触发静态代码块
* 触发静态代码块:
* 类加载机制:类加载的时候,会触发静态代码块
* 加载【class文件->jvm虚拟机的class对象】
* 连接【验证(检查文件类型)->准备(静态变量默认值)->解析(触发静态代码块)】
* 初始化(静态属性赋真实值)
* 触发类加载:
* 1.new关键字
* 2.调用静态方法
* 3.调用静态属性
* 4.接口1.8 default默认实现
* 5.反射
* 6.子类触发父类
* 7.程序的入口main
*/
//DriverManager.registerDriver(new Driver());
//换了个版本就不行了,不灵活
//new Driver();
2.获取数据库连接
//1.
Connection conn = DriverManager.getConnection(url, username, password);
//2.
Properties info = new Properties();
info.put("user","root");
info.put("password","root");
Connection connection1 = DriverManager.getConnection();
//3.
//参数:jdbc:数据库软件名://ip:port/数据库?key=value&key=value
//例如: jdbc:mysql://localhost:3306/table1?user=root&password=root
Connection connection2 = DriverManager.getConnection();
核心属性
- 数据库软件所在的主机的ip地址:localhost | 127.0.0.1
- 数据库软件所在的主机的端口号 :3306
- 所连接的具体库
- 连接的账号 username
- 连接的密码 password
- 可选的信息
url 语法:[mysql,oracle]://ip地址|主机名:port端口号/数据库名
例如:"jdbc:mysql://127.0.0.1:3306/table1"
3.定义sql
Statement stmt = conn.createStatement();
//conn是获取的数据库连接
作用:可以发送sql语句到数据库,并返回结果
SQL分类:
- DDL(容器创建,修改,删除)
- DML(插入,修改,删除)
- DQL(查询)
- DCL(权限控制)
- TPL事务控制语言)
int executeUpdate(String sql);
执行DML、DDL语句
返回值:DML语句影响的行数;DDL语句执行后,执行成功也可能返回0;
ResultSet executeQuery(sql);
执行DQL语句
返回值:ResultSet结果集对象;
4.发送sql语句
//发送sql语句
ResultSet resultSet = stmt.executeQuery(sql);
5.处理数据
boolean flag = resultSet.next();
//逐行获取数据
resultSet,get类型(String columnLabel | int columnIndex);
//columnLabel :列名 如果有别名,写别名
//columnIndex : 列的下角标获取 从左向右 从1开始
6.关闭资源
//释放资源
resultSet.close();
stmt.close();
conn.close();
优化
preparedstatment(利用预编译)
作用:防止sql注入攻击
- 编写SQL语句结果 不包含动态值的部分的语句,动态之部分使用占位符 ? 替代 注意: ? 只能替代动态值
- 创建preparedStatement,并传入动态值
- 动态值 占位符 赋值 ? 单独赋值即可
- 发送SQL语句即可,并获取返回结构
String sql = "select * from t_user where account = ? and password = ?;";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//单独的占位符进行赋值
/**
* 参数1:index 占位符的位置 从左向右数 从1开始 账号 ? 1
* 参数2:object 占位符的值 可以设置为任何类型的数据,避免了我们拼接和类型更加丰富
*/
preparedStatement.setObject(1,account);
preparedStatement.setObject(2,password);
练习(增删查改)
package com.ln.jdbc;
import com.mysql.cj.util.DnsSrv;
import org.junit.Test;
import java.sql.*;
import java.util.*;
public class StatementUserLogin {
@Test
public void testInsert() throws Exception {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/tabe1",
"root",
"@950908964xLN,"
);
String sql = "insert into 用户(uid,username,money) values (?,?,?);";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setObject(1,3);
preparedStatement.setObject(2,"小美");
preparedStatement.setObject(3,2000);
int i = preparedStatement.executeUpdate();
if(i>0){
System.out.println("ok");
}
else{
System.out.println("error");
}
preparedStatement.close();
connection.close();
}
@Test
public void testUpdate() throws Exception {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/tabe1",
"root",
"@950908964xLN,"
);
String sql = "update 用户 set username=? where uid = ?;";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setObject(1,"小强");
preparedStatement.setObject(2,"2");
int i = preparedStatement.executeUpdate();
if(i>0){
System.out.println("修改成功");
}
else{
System.out.println("修改失败");
}
preparedStatement.close();
connection.close();
}
@Test
public void testDelete() throws Exception {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/tabe1",
"root",
"@950908964xLN,"
);
String sql = "delete from 用户 where uid=?;";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setObject(1,2);
int i = preparedStatement.executeUpdate();
if(i>0){
System.out.println("ok");
}
else{
System.out.println("error");
}
preparedStatement.close();
connection.close();
}
@Test
public void testSelect() throws Exception {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/tabe1",
"root",
"@950908964xLN,"
);
String sql = "select uid,username,money from 用户;";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
ResultSet resultSet = preparedStatement.executeQuery();
List<Map>list = new ArrayList<>();
//装的是当前结果集列的信息对象(可以获得列的名称和数量)
ResultSetMetaData metaData = resultSet.getMetaData();
//有了这个之后可以水平遍历列
int columnCount = metaData.getColumnCount();
while(resultSet.next()){
Map map = new HashMap();
/**
map.put("id",resultSet.getInt("uid"));
map.put("username",resultSet.getString("username"));
map.put("money",resultSet.getInt("money"));
list.add(map);
*/
//注意要从1开始,并且小于等于columnCount
for (int i = 1; i <= columnCount; i++) {
//获取指定列下角标的值
Object value = resultSet.getObject(i);
//获取指定列下角标的列的名称
String columnLabel = metaData.getColumnLabel(i);
map.put(columnLabel,value);
}
list.add(map);
}
System.out.println("list = " + list);
resultSet.close();
preparedStatement.close();
connection.close();
}
}
连接池
首先安装jar包
- 创建一个druid连接池对象
- 设置连接池参数
- 获取连接【通用方法,所有连接池都一样】
- 回收连接【通用方法,所有连接池都一样】
//连接池对象
DruidDataSource dataSource = new DruidDataSource();
//设置参数
//必须 连接数据库驱动类的全限定符【注册驱动】 | url | user | password
dataSource.seUrl("jdbc:mysql://localhost:3306/tabe1");
dataSource.setUsername("账号");
dataSource.setPassword("密码");
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
//非必须 初始化连接数量,最大的连接数量
dataSource.setInitialSize();//初始化连接数量
dataSource.setMaxActive();//最大的数量
//获取连接
Connection connection = dataSource.getConnection();
//回收连接
connection.close();