1.JDBC是什么?
JDBC就是 Java Database connectivity Java数据库连接规范(也可以说是一套接口) 是有Sun公司提供的 基友四个核心类;
2.核心类
DriverManager 创建数据库连接
Connection 连接类
Statement 执行sql语句
ResultSet 结果集
3. 连接步骤
1.注册驱动
2.获取连接 Connection
3.获取sql语句的执行对象 Statement
4.执行sql语句 返回结果集ResultSet
5.处理结果集
6.关闭资源
4. 创建数据库连接三种方法
1. Class.forName(“com.mysql.jdbc.Driver”);
DriverManager.registerDriver(new Driver());
这种注册方式 相当于注册了两次
Driver类内部的静态代码块已经注册一遍
这个方法直接把该类加载到内存中 参数是全限定类名
包名加类名
2.Properties info = new Properties();
//添加用户名密码
//注意建值拼写
info.setProperty(“user”, “root”);
info.setProperty(“password”, “123456”);
Connection connection=DriverManager.getConnection(url,info);
3.//获取连接方式3 相当于使用get请求 携带参数访问连接(相对于前两种比较常用)
String url2= “jdbc:mysql://localhost:3306/myjdbc?user=root&password=123456”;
Connection connection =DriverManager.getConnection(url2);
5.获取执行SQL语句的对象 statement
Statement statement = connection.createStatement();
// 执行sql语句 返回结果集
// 结果集中的索引 要和查询语句中的子弹对应
String sql = “select * from users”;
6.// 处理结果集
// 循环遍历结果集 输出结果
// 有记录 next()方法 返回true 反之
while (resultSet.next()) {
// 打印数据
// 查询数据库 时 索引从一开始
System.out.println(resultSet.getObject(1));
System.out.println(resultSet.getObject(2));
System.out.println(resultSet.getObject(3));
System.out.println(resultSet.getObject(4));
System.out.println(resultSet.getObject(5));
System.out.println(“———————————”);
}
7.// 关闭资源
resultSet.close();
statement.close();
connection.close();
} catch (Exception e) {
8.sql注入
Select * From users where name = ‘231232asd’
and password =’asdasd’ or ‘1’=’1’;
9. 封装方法
在scr下新建一个dbinfo.properties
填写一下内容
文件内容:
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/myjdbc
user=用户名
password=数据库连接密码
注意: 不要加入空格等无用字符
新建一个工具类JDBCUtil,用来写方法,配置dbinfo.properties文件。
9.代码实例
public class JDBCUtil {
private static String driverClass;
private static String url;
private static String user;
private static String password;
// 使用静态代码块加载驱动 读取配置文件
static {
// 使用系统类来读取配置文件
ResourceBundle resourceBundle = ResourceBundle.getBundle(“dbinfo”);
// 获取文件中的数据
driverClass = resourceBundle.getString(“driverClass”);
url = resourceBundle.getString(“url”);
user = resourceBundle.getString(“user”);
password = resourceBundle.getString(“password”);
}
// 获取数据库连接方法
public static Connection getConnection() throws ClassNotFoundException, SQLException {
return DriverManager.getConnection(url, user, password);
}
// 关闭的方法
public static void closeAll(ResultSet resultSet, PreparedStatement preparedStatement, Connection connection) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("资源被占用,关闭失败");
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("资源被占用,关闭失败");
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("资源被占用,关闭失败");
}
}
}
}