java:JDBC的使用方式
学习目标
JDBC:
1. 概念:Java DataBase Connectivity Java 数据库连接, Java语言操作数据库
JDBC本质:其实是官方(sun公司)定义的一套操作所有关系型数据库的规则,即接口。
各个数据库厂商去实现这套接口,提供数据库驱动jar包。我们可以使用这套接口(JDBC)编程,真正执行的代码是驱动jar包中的实现类。
2. 快速入门:
步骤:
1. 导入驱动jar包 mysql-connector-java-5.1.37-bin.jar
1.复制mysql-connector-java-5.1.37-bin.jar到项目的libs目录下
2.右键-->Add As Library
2. 注册驱动
3. 获取数据库连接对象 Connection
4. 定义sql
5. 获取执行sql语句的对象 Statement
6. 执行sql,接受返回结果
7. 处理结果
8. 释放资源
实现连接数据库:
public class JDBCDemo1 { public static void main(String[] args) throws SQLException, ClassNotFoundException { //1. 导入驱动jar包 //2.注册驱动 Class.forName("com.mysql.jdbc.Driver"); //3.获取数据库连接对象 Connection conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root"); String sql="insert into user values(null,'root','root')"; //4.定义sql语句 //5.获取执行sql的对象 Statement Statement stmt = conn.createStatement(); //6.执行sql int count = stmt.executeUpdate(sql); //7.处理结果 System.out.println(count); //8.释放资源 stmt.close(); conn.close(); } }
Connection:数据库连接对象
1. 功能:
1. 获取执行sql 的对象
* Statement createStatement()
* PreparedStatement prepareStatement(String sql)
2. 管理事务:
* 开启事务:setAutoCommit(boolean autoCommit) :调用该方法设置参数为false,即开启事务
* 提交事务:commit()
* 回滚事务:rollback()
3. Statement:执行sql的对象
1. 执行sql
1. boolean execute(String sql) :可以执行任意的sql 了解
2. int executeUpdate(String sql) :执行DML(insert、update、delete)语句、DDL(create,alter、drop)语句
* 返回值:影响的行数,可以通过这个影响的行数判断DML语句是否执行成功 返回值>0的则执行成功,反之,则失败。
3. ResultSet executeQuery(String sql) :执行DQL(select)语句
实现增删改查
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; /** * account表 添加一条记录 insert 语句 */ public class JDBCDemo2 { public static void main(String[] args) { Statement stmt = null; Connection conn = null; try { //1. 注册驱动 Class.forName("com.mysql.jdbc.Driver"); //2. 定义sql String sql = "insert into account values(null,'王五',3000)"; //3.获取Connection对象 conn = DriverManager.getConnection("jdbc:mysql:///db3", "root", "root"); //4.获取执行sql的对象 Statement stmt = conn.createStatement(); //5.执行sql int count = stmt.executeUpdate(sql);//影响的行数 //6.处理结果 System.out.println(count); if(count > 0){ System.out.println("添加成功!"); }else{ System.out.println("添加失败!"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }finally { //stmt.close(); //7. 释放资源 //避免空指针异常 if(stmt != null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn != null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; /** * account表 修改记录 */ public class JDBCDemo3 { public static void main(String[] args) { Connection conn = null; Statement stmt = null; try { //1. 注册驱动 Class.forName("com.mysql.jdbc.Driver"); //2.获取连接对象 conn = DriverManager.getConnection("jdbc:mysql:///db3", "root", "root"); //3.定义sql String sql = "update account set balance = 1500 where id = 3"; //4.获取执行sql对象 stmt = conn.createStatement(); //5.执行sql int count = stmt.executeUpdate(sql); //6.处理结果 System.out.println(count); if(count > 0){ System.out.println("修改成功!"); }else{ System.out.println("修改失败"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { //7.释放资源 if(stmt != null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn != null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
import cn.itcast.util.JDBCUtils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; /** * account表 删除一条记录 */ public class JDBCDemo4 { public static void main(String[] args) { Connection conn = null; Statement stmt = null; try { //1. 注册驱动 Class.forName("com.mysql.jdbc.Driver"); //2.获取连接对象 conn = DriverManager.getConnection("jdbc:mysql:///db3", "root", "root"); //conn = JDBCUtils.getConnection("jdbc:mysql:///db3", "root", "root"); //3.定义sql String sql = "delete from account where id = 3"; //4.获取执行sql对象 stmt = conn.createStatement(); //5.执行sql int count = stmt.executeUpdate(sql); //6.处理结果 System.out.println(count); if(count > 0){ System.out.println("删除成功!"); }else{ System.out.println("删除失败"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { //7.释放资源 if(stmt != null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn != null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; /** * 执行DDL语句 */ public class JDBCDemo5 { public static void main(String[] args) { Connection conn = null; Statement stmt = null; try { //1. 注册驱动 Class.forName("com.mysql.jdbc.Driver"); //2.获取连接对象 conn = DriverManager.getConnection("jdbc:mysql:///db3", "root", "root"); //3.定义sql String sql = "create table student (id int , name varchar(20))"; //4.获取执行sql对象 stmt = conn.createStatement(); //5.执行sql int count = stmt.executeUpdate(sql); //6.处理结果 System.out.println(count); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { //7.释放资源 if(stmt != null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn != null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
import java.sql.*; /** * 执行DDL语句 */ public class JDBCDemo6 { public static void main(String[] args) { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { //1. 注册驱动 Class.forName("com.mysql.jdbc.Driver"); //2.获取连接对象 conn = DriverManager.getConnection("jdbc:mysql:///db3", "root", "root"); //3.定义sql String sql = "select * from account"; //4.获取执行sql对象 stmt = conn.createStatement(); //5.执行sql rs = stmt.executeQuery(sql); //6.处理结果 //6.1 让游标向下移动一行 rs.next(); //6.2 获取数据 int id = rs.getInt(1); String name = rs.getString("name"); double balance = rs.getDouble(3); System.out.println(id + "---" + name + "---" + balance); //6.1 让游标向下移动一行 rs.next(); //6.2 获取数据 int id2 = rs.getInt(1); String name2 = rs.getString("name"); double balance2 = rs.getDouble(3); System.out.println(id2 + "---" + name2 + "---" + balance2); //6.1 让游标向下移动一行 rs.next(); //6.2 获取数据 int id3 = rs.getInt(1); String name3 = rs.getString("name"); double balance3 = rs.getDouble(3); System.out.println(id3 + "---" + name3 + "---" + balance3); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { //7.释放资源 if(rs != null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(stmt != null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn != null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
ResultSet:结果集对象,封装查询结果
* boolean next(): 游标向下移动一行,判断当前行是否是最后一行末尾(是否有数据),如果是,则返回false,
如果不是则返回true
* getXxx(参数):获取数据
* Xxx:代表数据类型 如: int getInt() , String getString()
* 参数:
1. int:代表列的编号,从1开始 如: getString(1)
2. String:代表列名称。 如: getDouble("balance")
* 注意:
* 使用步骤:
1. 游标向下移动一行
2. 判断是否有数据
3. 获取数据
//循环判断游标是否是最后一行末尾。
while(rs.next()){
//获取数据
//6.2 获取数据
int id = rs.getInt(1);
String name = rs.getString("name");
double balance = rs.getDouble(3);
System.out.println(id + "---" + name + "---" + balance);
}
PreparedStatement:执行sql的对象
PreparedStatement:执行sql的对象 1. SQL注入问题:在拼接sql时,有一些sql的特殊关键字参与字符串的拼接。会造成安全性问题 1. 输入用户随便,输入密码:a' or 'a' = 'a 2. sql:select * from user where username = 'fhdsjkf' and password = 'a' or 'a' = 'a' 2. 解决sql注入问题:使用PreparedStatement对象来解决 3. 预编译的SQL:参数使用?作为占位符 4. 步骤: 1. 导入驱动jar包 mysql-connector-java-5.1.37-bin.jar 2. 注册驱动 3. 获取数据库连接对象 Connection 4. 定义sql * 注意:sql的参数使用?作为占位符。 如:select * from user where username = ? and password = ?; 5. 获取执行sql语句的对象 PreparedStatement Connection.prepareStatement(String sql) 6. 给?赋值: * 方法: setXxx(参数1,参数2) * 参数1:?的位置编号 从1 开始 * 参数2:?的值 7. 执行sql,接受返回结果,不需要传递sql语句 8. 处理结果 9. 释放资源 5. 注意:后期都会使用PreparedStatement来完成增删改查的所有操作 1. 可以防止SQL注入 2. 效率更高
设置Bean类
public class UserDao { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
连接数据库
import com.web.domain.UserDao; import java.sql.*; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class JDBCDemo2 { public static void main(String[] args) throws SQLException, ClassNotFoundException { Class.forName("com.mysql.jdbc.Driver"); Connection conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root"); String sql="select *from user"; PreparedStatement pstmt=conn.prepareStatement(sql); conn.setAutoCommit(false); ResultSet rs=pstmt.executeQuery(); conn.commit(); List list=new ArrayList<UserDao>(); while(rs.next()){ String username=rs.getString("username"); String password=rs.getString("password"); UserDao userDao=new UserDao(); userDao.setUsername(username); userDao.setPassword(password); list.add(userDao); } conn.close(); pstmt.close(); Iterator<UserDao> it=list.iterator(); while(it.hasNext()){ UserDao userDao= it.next(); System.out.println(userDao.getUsername()+"=================="+userDao.getPassword()); } } }
优化
import com.web.domain.UserDao; import java.sql.*; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class JDBCDemo3 { public static void main(String[] args) throws SQLException { Connection conn=null; PreparedStatement pstmt=null; ResultSet rs=null; try { Class.forName("com.mysql.jdbc.Driver"); conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root"); String sql="select *from user"; pstmt=conn.prepareStatement(sql); conn.setAutoCommit(false); rs=pstmt.executeQuery(); conn.commit(); List list=new ArrayList<UserDao>(); while(rs.next()){ String username=rs.getString("username"); String password=rs.getString("password"); UserDao userDao=new UserDao(); userDao.setUsername(username); userDao.setPassword(password); list.add(userDao); } Iterator<UserDao> it=list.iterator(); while(it.hasNext()){ UserDao userDao= it.next(); System.out.println(userDao.getUsername()+"=================="+userDao.getPassword()); } }catch (Exception e){ e.printStackTrace(); }finally { if(conn!=null) conn.close(); if(pstmt!=null) pstmt.close(); } } }
设置JDBC的连接工具类
import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.sql.*; import java.util.Properties; //JDBC工具类 public class JDBCutils { private static String url; private static String user; private static String password; private static String driver; //文件的读取,只需要读取一次即可拿到这些值。使用静态代码块 static { //读取资源文件,获取值。 try { //1. 创建Properties集合类。 Properties pro = new Properties(); //获取src路径下的文件的方式--->ClassLoader 类加载器 ClassLoader classLoader=JDBCutils.class.getClassLoader(); URL res=classLoader.getResource("jdbc.properties"); String path=res.getPath(); //2. 加载文件 pro.load(new FileReader(path)); //3. 获取数据,赋值 url = pro.getProperty("url"); user = pro.getProperty("user"); password = pro.getProperty("password"); driver = pro.getProperty("driver"); //4. 注册驱动 Class.forName(driver); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * 获取连接 * @return 连接对象 */ public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url, user, password); } /** * 释放资源 * @param stmt * @param conn */ public static void close(Statement stmt, Connection conn){ if( stmt != null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if( conn != null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } /** * 释放资源 * @param stmt * @param conn */ public static void close(ResultSet rs, Statement stmt, Connection conn){ if( rs != null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if( stmt != null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if( conn != null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
jdbc文件
url=jdbc:mysql://localhost:3306/test user=root password=root driver=com.mysql.jdbc.Driver
连接
import com.web.domain.UserDao; import com.web.utils.JDBCutils; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class JDBCDemo4 { public static void main(String[] args) throws SQLException { Connection conn=null; PreparedStatement pstmt=null; ResultSet rs=null; conn= JDBCutils.getConnection(); String sql="select *from user"; conn.setAutoCommit(false); pstmt=conn.prepareStatement(sql); rs=pstmt.executeQuery(); conn.commit(); List list=new ArrayList<UserDao>(); while(rs.next()){ String username=rs.getString("username"); String password=rs.getString("password"); UserDao userDao=new UserDao(); userDao.setUsername(username); userDao.setPassword(password); list.add(userDao); } Iterator<UserDao> it=list.iterator(); while(it.hasNext()){ UserDao userDao= it.next(); System.out.println(userDao.getUsername()+"=================="+userDao.getPassword()); } JDBCutils.close(rs,pstmt,conn); } }