JDBC连接数据库
简单连接数据库
- 注册驱动 - 加载Driver类
- 获取连接 - 得到Connection
- 执行增删改查 - 发送SQL给mysql执行
- 释放资源 - 关闭相关连接
package com.hspedu.jdbc;
//在mysql8.0版本之上的 需要修改url在里面添加时区的概念
//所以要记得修改url 如果是5.7版本的不用添加
import com.mysql.cj.jdbc.Driver;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
//第一个jdbc程序
public class Jdbc01 {
public static void main(String[] args) throws SQLException {
//前置工作 在项目下建立一个文件夹 比如libs 将mysql.jar拷贝到该目录下 点击add as library加入到项目中
//1.注册驱动
Driver driver = new Driver();//创建了一个驱动
//2.获取连接
//1. jdbc:mysql:// 规定好表示协议 通过jdbc的方式连接数据库
//2. localhost 主机 可以时IP地址
//3. 3306 表示mysql监听的端口
//4. hsp_db02 连接到数据库中的具体某一个数据库
//5. mysql连接的本质就是socket连接
String url="jdbc:mysql://localhost:3306/hsp_db02?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true";
//将用户名和密码放入到Properties对象
Properties properties=new Properties();
// user 和 password 是规定好的 后面的值根据实际情况而定
properties.setProperty("user","root");//用户
properties.setProperty("password","123456");//密码
Connection connect = driver.connect(url,properties);
//3.执行sql
//下面那个null是因为我连接的数据库属性id设置了自动增长 所以写为null
String sql="insert into actor values(null,'张三','男','2000-2-20',11110)";
//statement 用于执行静态SQL语句并返回其生成的结果的对象
Statement statement = connect.createStatement();
//如果是DML语句 返回的就是受影响的行数 如果然后值rows值为1表示添加成功 返回0表示添加失败
int rows=statement.executeUpdate(sql);
System.out.println(rows>0?"成功":"失败");
//4.关闭连接
statement.close();
connect.close();
}
}
MySQL Connector/J官网下载地址:https://downloads.mysql.com/archives/c-j/