JDBC
【步骤】
1.加载驱动进行连接
方式一:通过第三方数据库连接驱动[MySQL/Oracle]配置文件,读取相对路径Jar包,使用DriverManger类
方式二:通过第三方数据库连接池[DBCP/C3P0/Druid] Jar 以及 Proerties配置文件,读取相对路径Jar包,使用DataSource类
2.获取Connection连接对象
3.操作静态Sql语句执行Statement对象,或预编译Sql语句的PreparedStatement对象
4.获得结果集ResultSet 或 受影响行affectedRow
5.释放Sql语句执行资源 Statement 或 PerparedStatement
6.释放Connection连接资源,若使用了数据库连接池则对close()方法进行了加强,仅清除数据归还连接池,并不会断开当前连接。
>> Statement
>>> 1.resource资源路径下创建jdbc.properties
文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///test_05?useSSL=false&useServerPrep=true
jdbc.userName=root
jdbc.password=root
【警告】使用Connection Jar包版本8.0需要和MySQL8.0数据库版本符合,否则不兼容将无法加载驱动
>>> 2.获取Connection与Statement 对象
public class DriverDemo {
public static void main(String[] args) throws Exception {
InputStream is = ClassLoader.getSystemResourceAsStream("jdbc.properties");
Properties prop = new Properties();
prop.load(is);
is.close();
Connection connection = DriverManager.getConnection(prop.getProperty("jdbc.url"),
pro.getProperty("jdbc.userName"),
pro.getProperty("jdbc.password"));
connection.setAutoCommit(false);
try {
connection.commit();
}catch (Exception e){
connection.rollback();
}
Statement statement = connection.createStatement();
statement.close();
connection.close();
}
}
>>> 获取单行row数据
int affectedRow = statement.executeUpdate("DMQ OR DDL SQL...");
ResultSet resultSet = statement.executeQuery("DQQ SQL...");
int resultInt = resultSet.getInt("salary");
int resultInt = resultSet.getInt(1);
>>> 获取多行rows数据
ArrayList<T> t = new ArrayList<>();
while (resultSet.next()) {
Account account = new Account(resultSet.getString("name"), Integer.valueOf(resultSet.getString("salary")));
accounts.add(account);
}
>> PreparedStatement
>>> 1.resource资源路径下创建dateSource.properties
文件
# 第三方数据库驱动路径
driverClassName=com.mysql.jdbc.Driver
# 统一资源标识符Url
url=jdbc:mysql:///test_05?useSSL=false&useServerPrepStmts=true
# 账户以及密码
username=root
password=root
# 初始化连接大小
initialSize=5
# 最大活跃连接
maxActive=10
# 最大等待时间(超过最大活跃连接时,最大等待时间)
maxWait=3000
>>> 2.获取DataSource与PreparedStatement 对象
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
Connection connection = dataSource.getConnection();
String sql = "INSERT INTO tb_brand VALUES (?,?,?,?,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
Class<? extends Brand> aClass = brand.getClass();
Field[] fields = aClass.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
fields[i].setAccessible(true);
preparedStatement.setObject(i + 1, fields[i].get(brand));
}
int i = preparedStatement.executeUpdate();
preparedStatement.close();
connection.close();