数据持久化(persistence):把数据保存到可掉电式存储设备中以供之后使用。
JDBC:就是使用java编程调用MySQL关系型数据CURD;本质就是sun公司为各大关系型数据库厂商提供的接口(API)。
两个库:
java.sql
javax.sql
java操作MySQL的过程
1、保证有个有效的MySQL数据库软件在运行
2、创建一个项目
3、将java操作MySQL的驱动包添加到项目中
Oracle的驱动:oracle.jdbc.driver.OracleDriver
mySql的驱动: com.mysql.jdbc.Driver
几种常用数据库的JDBC URL
对于 Oracle 数据库连接,采用如下形式:
jdbc:oracle:thin:@localhost:1521:db_ljh
对于 SQLServer 数据库连接,采用如下形式:
jdbc:microsoft:sqlserver//localhost:1433; DatabaseName=sid
对于 MYSQL 数据库连接,采用如下形式:
jdbc:mysql://localhost:3306/ db_ljh
import static org.junit.jupiter.api.Assertions.*;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import java.util.Properties;
import org.junit.jupiter.api.Test;
class TestConnection {
@Test
void testConnection() throws SQLException{
Driver diver=new com.mysql.jdbc.Driver();
//连接的协议
String url="jdbc:mysql://localhost:3306/db_hero";
//创建properties对象,设置用户名和密码。
Properties info=new Properties();
info.setProperty("user", "root");
info.setProperty("password", "root");
Connection con=diver.connect(url, info);
System.out.println(con);
}
@Test
void testConnect02() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
/**
* 反射 string driver="com.mysql.jdbc.Driver";
*/
String path ="org.gjt.mm.mysql.Driver";
//完整路径路径===》对应对象 ,反射
Class driver=Class.forName(path);
Driver dri=(Driver) driver.newInstance();
//连接协议
String url="jdbc:mysql://localhost:3306/db_hero";
//创建properties对象,设置用户名和密码。
Properties info=new Properties();
info.setProperty("use", "root");
info.setProperty("password", "root");
Connection conn=dri.connect(url, info);
System.out.println(conn);
}
}
com.mysql.jdbc.JDBC4Connection@df27fae