14 JDBC
JDBC java连接数据库
创建表
CREATE TABLE testdb(
id INT,
NAME VARCHAR(50)
);
连接数据库配置
<!--连接数据库-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
import java.sql.*;
public class TestJDBC {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//配置信息
String url="jdbc:mysql://localhost:3306/douyin";
String name="root";
String pass="11111111";
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库
Connection connection= DriverManager.getConnection(url,name,pass);
//3.编写sql
String sql="select * from testdb";
//4.预编译 使用PreparedStatement可防止sql注入
PreparedStatement preparedStatement=connection.prepareStatement(sql);
//5.执行sql
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next())
{
System.out.println("name="+resultSet.getString("name"));
System.out.println("name="+resultSet.getString("id"));
}
//6.关闭连接,释放资源
preparedStatement.close();
connection.close();
}
}
JDBC步骤(PreparedStatement)
加载驱动–》连接数据库–》编写sql–》预编译sql–》执行sql–》释放资源,关闭连接
事务
要么都成功,要么都失败
ACID原则:保证数据的安全
开启事务–》事务提交commit()–》事务回滚rollback()–》关闭事务
import org.junit.jupiter.api.Test;
import java.sql.*;
public class TestJDBC2 {
@Test
public void updateData()
{
//配置信息
String url="jdbc:mysql://localhost:3306/douyin";
String name="root";
String pass="11111111";
Connection connection=null;
//1.加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库
connection= DriverManager.getConnection(url,name,pass);
//3.通知数据库开启事务
connection.setAutoCommit(false);
//4.编写sql
String sql="update testdb set name='张三' where id=1";
//5.预编译 使用PreparedStatement可防止sql注入
PreparedStatement preparedStatement=connection.prepareStatement(sql);
//6.执行sql
preparedStatement.executeUpdate();
//7.提交事务
connection.commit();
//8.关闭连接,释放资源
preparedStatement.close();
connection.close();
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
e.printStackTrace();
}
}
}
Junit单元测试
依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
@Test注释只在方法上有效,只要加了这个注解的方法就可以直接运行。