jdbc学习笔记1
此文章为个人学习笔记,课程是看的b站的尚硅谷宋红康老师的教学视频。
准备工作
1.需要在电脑上安装mysql,java,需要下载jdbc的驱动
2.将数据库开启
3.将驱动导入idea
4.建立所需要操作的数据库
5.下面开始学习jdbc
jdbc
我将jdbc理解为,在java与数据库中间的一种便捷接口的集合,为了方便工程师对数据库的操作。将两种工具进行连接,提高效率。
建立连接(connection)
实现代码1:
public class ConnectionTest {
@Test
public void testConnection() throws SQLException {
Driver driver=new com.mysql.jdbc.Driver();//建立连接对象:为导入的插件中的driver对象
String url = "jdbc:mysql://localhost:3306/jdbc_learn";//jdbc:mysql,协议 localhost是主机地址,3006:端口号,/test是数据库名
Properties info = new Properties();//将用户名和密码封装到properties
info.setProperty("user","root");
info.setProperty("password","111111");
Connection connect = driver.connect(url, info);//通过url,用户名和密码进行连接数据库
}
第一步:需要表明所使用的驱动
第二步,完成需要连接的数据库信息的声明(其中的url按照驱动中规范进行声明)
第三步.使用连接器(connect)建立连接
逻辑理解
当需要建立连接时,需要使用连接器,驱动和目标数据库信息(当我们需要到达某地时交通工具和司机,以及目的地)
实现代码2:
使用映射将驱动类封装,为代码提供更好的移植性和健壮性
public void test2() throws Exception {
Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");//使用映射将使用的类封装为内部类
Driver driver= (Driver) aClass.newInstance();
String url ="jdbc:mysql://localhost:3306/jdbc_learn";
Properties info = new Properties();//将用户名和密码封装到properties
info.setProperty("user","root");
info.setProperty("password","111111");
Connection connection= driver.connect(url,info);
System.out.println(connection);
}
实现代码3
使用DriverManager类以及registerDriver,getConnection方法
DriverManager为工具类,其中包装了声明驱动的静态代码块,
@Test
public void test3() throws Exception {
//DriverManager
Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
DriverManager.registerDriver(driver);//registerDriver方法为注册一个驱动
Connection root = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_learn", "root", "111111");//getConnection方法为获取一个连接器
}
2.
public void test4() throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
//因为在DriverManager类中封装了注册驱动的静态代码块故,可以省略注册
Connection root = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_learn", "root", "111111");
System.out.println(root);
}
代码实现5;
提出问题,在上述方法中会在代码中显现数据库的密码以及非动态实现
1.将配置信息写入文件中调用某文件中的信息可以实现动态修改以及信息安全
以下为配置文件jdbc.porperties
user=root
password=111111
url=jdbc:mysql://localhost:3306/jdbc_learn
driverClass=com.mysql.jdbc.Driver
2.读取配置文件中的信息进行连接数据库
@Test
public void test5() throws Exception {
//将配置信息写到配置文件将其进行读取
InputStream resourceAsStream = ConbectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");//jdbc.properties为配置文件,使用加载器加载文件信息
Properties properties=new Properties();
properties.load(resourceAsStream);
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driverClass = properties.getProperty("driverClass");
Class.forName(driverClass);
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
总结
第一注册驱动,第二使用连接器(connection)连接器中声明目的数据库信息
建议使用第四种与第五种方式建立连接。
下一篇讲解statement,以及preparedstatement操作数据库
简朴最终页,无爱即使神