一、JDBC简介
1、JDBC是SUN公司为了简化操作数据推出一套规范。数据库厂商的驱动就是对JDBC的实现。
2、Java Data Base Connectivity(java数据库连接),它主要由接口组成。
java.sql.* javax.sql.* JDK中
数据库的驱动jar包 (mysql-connector-java-5.0.8-bin.jar )
二、JDBC的编码步骤
0、前提:拷贝数据库的驱动到构建路径中(classpath)
1、注册驱动
2、获取与数据库的链接
3、创建代表SQL语句的对象
4、执行SQL语句
5、如果是查询语句,需要遍历结果集
6、释放占用的资源
public class JdbcDemo1 {
public static void main(String[] args) throws SQLException {
// 1、注册驱动
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
// 2、获取与数据库的链接
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/day15", "root", ""); //没有密码则“” 空
// System.out.println(conn.getClass().getName()); 要想知道具体类型,就这么办
// 3、创建代表SQL语句的对象
Statement stmt = conn.createStatement();
// 4、执行SQL语句
ResultSet rs = stmt.executeQuery("select id,name,password,email,birthday from users");
// 5、如果是查询语句,需要遍历结果集
while (rs.next()) {
System.out.println("---------------------");
System.out.println(rs.getObject("id"));
System.out.println(rs.getObject("name"));
System.out.println(rs.getObject("password"));
System.out.println(rs.getObject("email"));
System.out.println(rs.getObject("birthday"));
}
// 6、释放占用的资源
rs.close();
stmt.close();
conn.close();
}
}
三、JDBC中常用的接口详解
1、DriverManager:
作用:
a、注册驱动:
方式一:(不建议使用)
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
原因:1、依赖具体驱动。2、导致驱动注册2遍
方式二:(建议)
Class.forName("com.mysql.jdbc.Driver");
b、获取与数据库的链接
url:SUN和数据库厂商间的协议。具体查阅数据库的文档。
public static Connection getConnection(String url,String user,String password)
throws SQLException
public static Connection getConnection(String url,Properties info)
throws SQLException
public static Connection getConnection(String url)
throws SQLException
2、Connection
所有的数据库操作都是基于链接之上的。
Statement createStatement():创建向数据库发送sql的statement对象。
//2、获取与数据库的链接
//方式一:
//Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day15", "root", "sorry");
//方式二:
//Properties props = new Properties();
//props.setProperty("user", "root");// 参数名:参考数据库的文档
//props.setProperty("password", "sorry");
//props.setProperty("useUnicode", "true");//编码有关的参数
//props.setProperty("characterEncoding", "utf8");
//Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day15",props);
//方式三
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day15?user=root&password=sorry");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day15?user=root&password=");
3、Statement
Statement stmt = conn.createStatement();
作用:代表SQL语句对象。可以向数据库发送任何的SQL语句
ResultSet executeQuery(String sql):sql一般都是查询语句
int executeUpdate(String sql):sql一般是DML语句。insert update delete。返回值,操作几条记录。
boolean execute(String sql):sql可以是任意的语句。返回值不是代表成功与否。如果是查询语句,就有结果集,返回true。没有返回结果集的,返回false。
4、ResultSet
作用:封装了查询的结果集
ResultSet rs = stmt.executeQuery("select id,name,password,email,birthday from users");
List<User> users = new ArrayList<User>();
while(rs.next()){
User user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("password"));
user.setEmail(rs.getString("email"));
user.setBirthday(rs.getDate("birthday"));
users.add(user);
}
boolean next():游标下移。返回值是有无记录
boolean previous():游标上移。
boolean absolute(int count):定位到指定的行。第一行是1。
void beforeFirst():移动游标到第一行的前面。
void afterLast():移动游标到最后一行的后面。
四、释放占用的资源
//释放资源
//JDBC编码的代码模板
public class JdbcDemo5 {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day15", "root", "sorry");
stmt = conn.createStatement();
rs = stmt.executeQuery("select id,name,password,email,birthday from users");
List<User> users = new ArrayList<User>();
while (rs.next()) {
User user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("password"));
user.setEmail(rs.getString("email"));
user.setBirthday(rs.getDate("birthday"));
users.add(user);
}
} catch (Exception e) {
e.printStackTrace();
} <br> finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
}
}
五、JDBC进行CRUD(增刪改查)操作
工具類:
<strong><span style="color: #ff0000;">getConnection() return conn; 獲取連接<br><br>配置文件放在 dbcgf.properties 中<br><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAbIAAAB6CAIAAABV3UEmAAATOUlEQVR4nO2d72scxxnH9+/Rq5Y41+iSOn2pV37ltyqIwtEUmjjUaSThJo1IgpIWfGohheZUAsWuCWpDDT5KcXyUvohfCJQU9U0ujRUIiSsSx8i1LVlB0xf7a55nZp6Z29u93ZO+Xx6MvDM7P3ZmP/fMzO5OpCAIgiBNUd0FgCAIapaARQiCIKIEi5998UC3/vVNGAwGO5lGsKiUio/WRmkoQHEb/euzuzAYrArLsRjfb7Xe79AIAhlhsIosxyKYOHUCGWGwKizS77Ea73CogIBFGKwKi7IbrN47HCqm/vXNj3buwmCwEg1YnG4BizBY6ebB4tU3v2O1Cd74kCRgEQYr3fxYPHj0LbPtq8+AjA1R//rmRzvfwGCwEs2Dxb+sfvfhweH+wbf7B4fpH99+/P6Ff4eTcXA+muvtKKXUTm8uOj8IvN93enNRFIXHr1s7vbm0noX1TCrvwUzAIgxWunmw+O7rj93fP1y79MErv7v+01f//MOf//HB/uHOzYsfv39h++qP3339Mf+9XgiLIxG0ESoJi94/mIBFGKx082Dx0qun9u4f3ntwuPfg8N6Dw3v3D+89yO3Sa6f893ohLOYnNVol01tnH/MQgUUYbGLmweI7K4/fvX+4dumDX7/zz1d/P7jwm7/97I2rP1nZ+NHyn+7+7/Cdlcf99zqwOIqs+HMxUSnVv7754a1vYDBYiebB4tsvt77ee/T13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FFEPzZHQsp0dtPCXHpA/c2isEbxGCpksVYHH3RleH4ihYZMwx/SuKmAJzi1oe/U7U7nTaUaevHbRSz/D5BCyajiawCEHTpfKxyHYsoLoS7i0ao1U3Yvi+gHJov5PukNDuDofddrpdgmsMPZq36MYiBtEQNB2axFsuwd6ijhxzCyvR8xphqjFGYL/bzjjY6SeoVFbskYy9W60ae9HAW4Sg6VKDsMgWj8l/U0+LBAuLNWIonXc0kratRLOBfcimrcNuOx6kA4sQNF2qHYvOiUManox39SjyvoBCKHPikpjcMXWMcX17CuanplOVwCIETZfq/FSEuO4MQRBUj4BFCIIgImARgiCICFiEIAgiwmdoIQiCiIBFCIIgImARgiCICFiEIAgi+j9aHtw6gUgHSgAAAABJRU5ErkJggg==" alt=""><br>release () 施放資源<br></span></strong>
//工具类
public class JdbcUtil {
private static String driverClass;
private static String url;
private static String user;
private static String password;
static{
try {
ClassLoader cl = JdbcUtil.class.getClassLoader();
InputStream in = cl.getResourceAsStream("dbcfg.properties");
Properties props = new Properties();
props.load(in);
driverClass = props.getProperty("driverClass");
url = props.getProperty("url");
user = props.getProperty("user");
password = props.getProperty("password");
Class.forName(driverClass);
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
public static Connection getConnection() throws Exception{
Connection conn = DriverManager.getConnection(url,user, password);
return conn;
}
public static void release(ResultSet rs,Statement stmt,Connection conn){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if(conn!=null){
try {
conn.close();
] catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
}
測試:
package com.yif.jdbc;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import org.junit.Test;
import com.yif.util.JdbcUtil;
public class JdbcDemo6 {
@Test
public void testAdd(){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
conn = JdbcUtil.getConnection();
stmt = conn.createStatement();
stmt.executeUpdate("insert into users (name,password,email,birthday) values ('范青霞','123','fqx@itcast.cn','2000-10-01')");
}catch(Exception e){
throw new RuntimeException(e);
}finally{
JdbcUtil.release(rs, stmt, conn);
}
}
@Test
public void testUpdate(){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
conn = JdbcUtil.getConnection();
stmt = conn.createStatement();
stmt.executeUpdate("update users set password=111 where id=4");
}catch(Exception e){
throw new RuntimeException(e);
}finally{
JdbcUtil.release(rs, stmt, conn);
}
}
@Test
public void testDelete(){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
conn = JdbcUtil.getConnection();
stmt = conn.createStatement();
stmt.executeUpdate("delete from users where id=1");
}catch(Exception e){
throw new RuntimeException(e);
}finally{
JdbcUtil.release(rs, stmt, conn);
}
}
}
sql 注入 :
1、用户的表单输入域:防止一些特殊字符。
2、对密码加密:MD5加密
PreparedStatement接口
1、支持SQL的预编译。得到该对象时,就必须给他SQL语句。
2、支持参数占位符: ? 一个问号代表着一个参数。
注:能用PreparedStatement就不要用Statement。