什么是JDBC?
Java数据库连接,(Java Database Connectivity,简称JDBC)是Java语言中用来规范客户端程序如何来访问数据库的应用程序接口,提供了诸如查询和更新数据库中数据的方法。JDBC也是Sun Microsystems的商标。我们通常说的JDBC是面向关系型数据库的。
1、首先准备数据库表和数据
CREATE TABLE users( `id` INT PRIMARY KEY, `name` VARCHAR(40), `password` VARCHAR(40), `email` VARCHAR(60), `birthday` DATE ); INSERT INTO users VALUES(1, '张三', '123456', 'zs@qq.com', '2020-03-18'); INSERT INTO users VALUES(2, '李四', '123456', 'ls@qq.com', '2020-03-18'); INSERT INTO users VALUES(3, '王五', '123456', 'ww@qq.com', '2020-03-18');
2、准备一个普通的Maven项目导入mysql-connector-java的依赖。
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.19</version> </dependency>
3、创建Testjdbc类
package com.allen.test; import java.sql.*; public class TestJdbc { public static void main(String[] args) throws ClassNotFoundException, SQLException { String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8"; String userName = "root"; String password = "li980314"; //1、加载jdbc驱动 Class.forName("com.mysql.cj.jdbc.Driver"); //2、连接数据库,代表数据库 Connection connection = DriverManager.getConnection(url, userName, password); //3、向数据库发送sql的对象statement : CRUD Statement statement = connection.createStatement(); //4、编写sql String sql = "select * from users"; //5、执行查询sql,返回一个ResultSet : 结果集 ResultSet resultSet = statement.executeQuery(sql); while(resultSet.next()){ System.out.println("id=" + resultSet.getObject("id")); System.out.println("name=" + resultSet.getObject("name")); System.out.println("password=" + resultSet.getObject("password")); System.out.println("email=" + resultSet.getObject("email")); System.out.println("birthday=" + resultSet.getObject("birthday")); } //6、关闭连接,释放资源 resultSet.close(); statement.close(); connection.close(); } }
运行测试:
4、预编译sql、防止sql注入加入占位符?
package com.allen.test; import java.sql.*; public class TestJdbc2 { public static void main(String[] args) throws ClassNotFoundException, SQLException { String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8"; String userName = "root"; String password = "li980314"; //1、加载jdbc驱动 Class.forName("com.mysql.cj.jdbc.Driver"); //2、连接数据库,代表数据库 Connection connection = DriverManager.getConnection(url, userName, password); //3、编写sql String sql = "insert into users values (?, ?, ?, ?, ?)"; //4、预编译 PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1, 4); preparedStatement.setString(2, "allen"); preparedStatement.setString(3, "123456"); preparedStatement.setString(4, "123@qq.com"); preparedStatement.setDate(5, new Date(new java.util.Date().getTime())); //5、执行sql //返回受影响行数,增,删,改都用executeUpdate int i = preparedStatement.executeUpdate(); if(i > 0){ System.out.println("插入成功!"); } //6、关闭连接,释放资源 preparedStatement.close(); connection.close(); } }
运行结果:
查看数据库: