1.JDBC
Java DataBase Connectivity (java数据库链接),即链接数据库的API
是一个接口或抽象类。
注:API : Application Programming Intergace (应用程序接口),即函数库
作用:连接数据库与程序的工具
使用步骤:
第0步: 导包
第1步:注册驱动 (仅仅做一次)
第2步:建立连接(Connection)
第3步:创建运行SQL的语句对象(Statement)
第4步:运行语句
第5步:处理运行结果(ResultSet)
第6步:释放资源
*格式固定
第一个类封装
第二个类工具包
public class Jdbc {
public static void main(String[] args) {
ResultSet resultSet=null;
Statement statement=null;
Connection conn=null;
try {
conn=JdbcUtil.getConnection();
//第3步:创建运行SQL的语句对象(Statement)
String sql="select * from student";
statement=conn.createStatement();
//第4步:运行语句,得到结果集
resultSet = statement.executeQuery(sql);
//第5步:处理运行结果(ResultSet)
while(resultSet.next()){
System.out.println("索引打印"+resultSet.getString(2));
System.out.println("标签打印"+resultSet.getString("name"));;
}
}catch (Exception e){
e.printStackTrace();
}
finally {
//优化的关闭资源
JdbcUtil.closeResultSet(resultSet);
JdbcUtil.closeResultSet(statement);
JdbcUtil.closeResultSet(conn);
}
}
}
工具包
public class JdbcUtil {
public static Connection getConnection() throws Exception {
//第1步:注册驱动 (仅仅做一次)
Class.forName("com.mysql.jdbc.Driver");
//第2步:建立连接(Connection)
Properties properties=new Properties();
properties.load(JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"));
String url = properties.getProperty("url");
String username = properties.getProperty("username");
String password = properties.getProperty("password");
return DriverManager.getConnection(url,username,password);
}
public static void closeResultSet(AutoCloseable autoCloseable){
try {
if(autoCloseable!=null){
autoCloseable.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
2.sql注入
通过恶意的sql命令非法获得或更改设计者不允许操作的数据!
3.事物
指访问并可能更新数据库中各种数据项的一个程序执行单元。
四大特性:ACID
原子性(atomicity)。一个事务是一个不可分割的工作单位,
事务中包括的操作要么都做,要么都不做。
一致性(consistency)。事务必须是使数据库从一个一致性状态
变到另一个一致性状态。一致性与原子性是密切相关的。
隔离性(isolation)。一个事务的执行不能被其他事务干扰。即一个事务内部的操作
及使用的数据对并发的其他事务是隔离的,并发执行的各个事务之间不能互相干扰。
持久性(durability)也称永久性(permanence),指一个事务一旦提交,
它对数据库中数据的改变就应该是永久性的。接下来的其他操作或故障不应该对其有任何影响。
4.连接池
存放常用数据库连接,提高效率
优点:
1.资源复用,避免频繁创建释放连接导致的大量性能开销,也增强了系统运行环境的平稳性
2.更快的响应速度,初始化过程中,连接池就已经船舰了若干连接对象放在池中,减少了响应时间
3.统一的连接管理,避免数据库连接遗漏,有超时强制回收设定,避免泄露资源