介绍JDBC以及连接数据库的5种方式
1 基本介绍Java数据库连接,(Java Database Connectivity,简称JDBC)是Java语言中用来规范客户端程序如何来访问数据库的应用程序接口,提供了诸如查询和更新数据库中数据的方法。
1 JDBC为访问不同的数据库提供了统一的接口,为使用者屏蔽了细节问题
2 使用JDBC可以连接任何提供了JDBC驱动程序的数据库系统
2 简单使用 2.1前置工作下载mysql.jar 加入项目下的libs目录
点击 add to project …加入到项目中
2.2 注册驱动Driver driver = new Driver();2.2 得到连接
//(1) jdbc:mysql:// 规定好表示协议,通过 jdbc 的方式连接 mysql
//(2) localhost 主机,可以是 ip 地址
//(3) 3306 表示 mysql 监听的端口
//(4) test 连接到 mysql dbms 的哪个数据库
//(5) mysql 的连接本质就是前面学过的 socket 连接
String url = "jdbc:mysql://localhost:3306/test";
//将 用户名和密码放入到 Properties 对象
Properties properties = new Properties();
//说明 user 和 password 是规定好,后面的值根据实际情况写
properties.setProperty("user", "root");// 用户
properties.setProperty("password", "123"); //密码
Connection connect = driver.connect(url, properties);
2.3 执行 sql
// sql String sql = "delete from actor where id = 1"; //statement 用于执行静态 SQL 语句并返回其生成的结果的对象 Statement statement = connect.createStatement(); int rows = statement.executeUpdate(sql); // 如果是 dml 语句,返回的就是影响行数 System.out.println(rows > 0 ? "成功" : "失败");2.4 关闭连接
statement.close(); connect.close();3 获取数据库连接的方式
方式1
Driver driver = new com.mysql.jdbcDriver();
String url = "jdbc:mysql://localhost:3306/test";
Properties properties = new Properties();
properties.setProperty("user", "root");// 用户
properties.setProperty("password", "123"); //密码
Connection connect = driver.connect(url, properties);
方式2
//方式1 属于静态加载,灵活性差
Class cls = Class.forName("com.mysql.jdbcDriver");
Driver driver = (Driver)cls.newInstance();
String url = "jdbc:mysql://localhost:3306/test";
Properties properties = new Properties();
properties.setProperty("user", "root");// 用户
properties.setProperty("password", "123"); //密码
Connection connect = driver.connect(url, properties);
方式3:使用DriverManager
Class cls = Class.forName("com.mysql.jdbcDriver");
Driver driver = (Driver)cls.newInstance();
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123";
DriverManager.registerDriver(driver);
Connection connect = DriverManager.getConnection(url,user,password);
方式4:Class.forName自动完成驱动注册
Class.forName("com.mysql.jdbcDriver");
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123";
DriverManager.registerDriver(driver);
Connection connect = DriverManager.getConnection(url,user,password);
方式5:使用最多
//通过 Properties 对象获取配置文件的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src\mysql.properties"));
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, user, password);



