一.概念
Java数据库的连接(Java访问数据库的规范)
二.作用
用来执行sql语句的API
三.使用
1.注册驱动:DriverManager
static {//随着类的加载而加载而且只会加载一次
try {
Properties properties = new Properties();
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");//表示在src下 的
properties.load(is);
String driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
2.获取连接:Connection
connection = DriverManager.getConnection(url, username, password);
3.创建SQL语句平台(执行SQL语句对象):Statement
Statement statement = connection.createStatement();
4.执行SQL语句:DML(executeUpdate,),DQL(executeQuEry)
String sql ="SELECT * FROM USER WHERE NAME ='"+username+"' AND password = '"+password+"'";
5.处理结果集RESULTSET
boolean execute = statement.execute(sql);
6.释放资源CLOSE
try {
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (statement != null) {
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
四.事物TRANSACTION
注册驱动
获取连接
获取到Statement
开启事务
使用Statement执行SQL
提交或回滚事务
关闭资源
转账案例:
Connection connection = null;
Statement statement = null;
try {
connection= JDBCUtils.getConnection();
statement = connection.createStatement();
connection.setAutoCommit(false);//开启事物
int a = 1/0;
String sql = "update account SET balance = balance - 100 WHERE NAME ='张三';";
int i = statement.executeUpdate(sql);
// connection.commit();
connection.rollback();
System.out.println("+++"+i);
} catch (SQLException e) {
e.printStackTrace();
}
JDBCUtils.close(null,statement,connection);
}