口诀:贾琏欲执事,在学习数据库连接的时候就有这个口诀,单纯为了好记
1.加(贾)载驱动
2.获取连(琏)接
3.SQL语(欲)句
4.执(执)行SQL
5.释(事)放资源 (释放链接要从小到大, 先释放后面的, 再释放前面的. 且必须放到finally里面)
一、代码
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
public class MysqlConnectionTest {
@Test
public void mysqlConnect(){
Connection conn = null;
//Statement statement = null;
PreparedStatement preparedStatement = null;
try {
String url = "jdbc:mysql://xxx.xx.xx.xx:3306/iwc_web_aihr_interview";
String user = "root"; //指定连接数据库的用户名
String password = "root"; //指定连接数据库的密码
String sql = "update hr_audition set candidate_id = ? where id =?";
// 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 2.获取连接对象
conn = DriverManager.getConnection(url, user, password);
// 3.创建语句欲执行对象
//statement = conn.createStatement();
preparedStatement = conn.prepareStatement(sql);
preparedStatement.setInt(1,20);
preparedStatement.setInt(2,26);
// 4.执行查询
//statement.executeUpdate(sql);
preparedStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 5.关闭连接,后建立的先关闭
//statement.close();
try {
if (preparedStatement != null){
preparedStatement.close();
}
}catch (Exception e){
e.printStackTrace();
}
try {
if (conn != null){
conn.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}
二、注意事项
1、加载驱动
mySql的驱动: com.mysql.jdbc.Driver, Oracle驱动: oracle.jdbc.driver.OracleDriver
2、SQL语句
sql语句有两种,一种是直接的sql语句,还有一种是使用占位符的预执行语句,建议使用占位符的预执行语句
3、执行sql
在jdbc中有3种执行sql的语句分别是execute,executeQuery和executeUpdate
execute执行增删改查操作
execute返回的结果是个boolean型,当返回的是true的时候,表明有ResultSet结果集,通常是执行了select操作,当返回的是false时,通常是执行了insert、update、delete等操作。execute通常用于执行不明确的sql语句。
executeQuery执行查询操作
executeQuery返回的是ResultSet结果集,通常是执行了select操作。
executeUpdate执行增删改操作
executeUpdate返回的是int型,表明受影响的行数,通常是执行了insert、update、delete等操作。
4、释放资源
这个不要忘,一般都是放在finally里面