今天闲来无事,将之前学习的笔记都整理一下,下面几篇博客都是用来记录JDBC的学习过程。
思路说明均在代码段的注释中。
连接数据库的几种方法(需要添加驱动):
1、最原始的方法
package demo01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class Connection_java1234 { private static String dri = "com.mysql.jdbc.Driver"; private static String url = "jdbc:mysql://localhost:3306/test" ; private static String user = "root"; private static String password = "root"; public static void main(String[] args){ //加载驱动 try { Class.forName(dri); System.out.println("加载驱动成功!"); } catch (ClassNotFoundException e) { e.printStackTrace(); System.out.println("加载驱动失败!"); } Connection con = null; try { con = DriverManager.getConnection(url,user,password); System.out.println("数据库连接成功!"); } catch (SQLException e) { e.printStackTrace(); System.out.println("数据库连接失败!"); }finally { try { con.close(); System.out.println("数据库关闭成功!"); } catch (SQLException e) { e.printStackTrace(); System.out.println("数据库关闭失败!"); } } } }
2、使用配置文件
java代码:
package demo01; import java.io.InputStream; import java.sql.DriverManager; import java.util.Properties; import org.junit.jupiter.api.Test; import com.mysql.jdbc.Connection; public class ConnectionTest { @Test public void testConnection5() throws Exception { //1. 加载配置文件 InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties"); Properties pros = new Properties(); pros.load(is); //2. 读取配置信息 String user = pros.getProperty("user"); String password = pros.getProperty("password"); String url = pros.getProperty("url"); String driverClass = pros.getProperty("driverClass"); //3. 加载驱动 Class.forName(driverClass); //4. 获取连接 Connection conn = (Connection) DriverManager.getConnection(url,user,password); System.out.println(conn); } }
配置文件jdbc.properties代码:
user=root password=root url=jdbc:mysql://localhost:3306/girls?rewriteBatchedStatements=true driverClass=com.mysql.jdbc.Driver