JDBC
JDBC是一种标准,一种规则,主要作用是使用java语言操作数据库的
JDBC这个标准中有很多的接口,接口中有很多方法
JDBC开发步骤以及详解
1.准备
1.导入jar包
mysql-connector-java-8.0.25.jar
2.四大核心对象
DriverManager类: 注册驱动 -> 我们需要知道我们操作的是哪款数据库
Connection接口:连接数据库用的
Statement接口:执行sql语句用的
ResultSet接口:结果集接口 -> 主要用于处理查询操作的
2.详细步骤
1.注册驱动:DriverManager类
2.获取连接:DriverManager类中的静态方法 -> 返回的是Connection
static Connection getConnection(String url, String user, String password)
url:数据库的地址
user:数据库用户名
password:数据库用户密码
3.准备sql语句:写sql
4.获取执行平台:Connection中的方法 -> 返回的是Statement对象 -> 主要用于执行sql语句
Statement createStatement();
5.执行sql:Statement中的方法
int executeUpdate(String sql) //针对于增删改 ResultSet executeQuery(String sql) //针对于查询
6.处理结果集:ResultSet接口中的方法:
boolean next() //判断有没有下一个元素
getxxx() //获取元素
7.关闭资源:
close方法
结果集关闭 ResultSet
执行平台关闭 Statement
连接关闭 Connection
3.具体例子
使用数据表
以下四个代码分别是增删改查的例子
public void insert() throws Exception {//1.注册驱动Class.forName("com.mysql.cj.jdbc.Driver");//2.获取连接,连接数据库String url = "jdbc:mysql://localhost:3306/day01";String name = "root";String password = "zsy20040820";Connection connection = DriverManager.getConnection(url, name, password);//3.准备sql语句String sql = "INSERT INTO `user`(username,password)VALUES('tom',123)";//4.获取执行平台Connection中的方法:// Statement createStatement()Statement st = connection.createStatement();//5.执行sql:Statement中的方法//int executeUpdate(String sql) -> 针对于增删改操作的int i = st.executeUpdate(sql);System.out.println("i = " + i);//6.由于增删改不需要处理结果集,所以直接关闭资源st.close();connection.close();}
public void delete()throws Exception{//1.注册驱动Class.forName("com.mysql.cj.jdbc.Driver");//2.获取连接,连接数据库String url = "jdbc:mysql://localhost:3306/day01";String name = "root";String password = "zsy20040820";Connection connection = DriverManager.getConnection(url, name, password);//3.准备sql语句String sql = "DELETE FROM `user` WHERE uid = 2";//4.获取执行平台Connection中的方法:// Statement createStatement()Statement st = connection.createStatement();//5.执行sql:Statement中的方法//int executeUpdate(String sql) -> 针对于增删改操作的int i = st.executeUpdate(sql);System.out.println("i = " + i);//6.由于增删改不需要处理结果集,所以直接关闭资源st.close();connection.close();}
public void update()throws Exception{//1.注册驱动Class.forName("com.mysql.cj.jdbc.Driver");//2.连接数据库String url = "jdbc:mysql://localhost:3306/day01";String name = "root";String password = "zsy20040820";Connection connection = DriverManager.getConnection(url, name, password);//3.准备sql语句String sql = "UPDATE`user` SET username = '刘涛' WHERE uid = 3";//4.获取执行平台Statement st = connection.createStatement();//5.执行int i = st.executeUpdate(sql);System.out.println("i = " + i);//6.由于增删改不需要处理结果集,所以直接关闭资源st.close();connection.close();}
public void select()throws Exception{//1.注册驱动Class.forName("com.mysql.cj.jdbc.Driver");//2.连接数据库Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/day01", "root", "zsy20040820");//3.准备sql语句String sql = "SELECT * FROM `user`";//4.获取执行平台Statement st = connection.createStatement();//5.执行ResultSet rs = st.executeQuery(sql);//6.处理结果集while (rs.next()){//String getString(String columnLabel) -> 获取指定列名的数据//int getInt(String columnLabel) -> 获取指定列名的数据//String getString(int columnIndex) -> 获取第几列的数据//int getInt(int columnIndex) -> 获取第几列的数据int uid = rs.getInt("uid");System.out.println("uid = " + uid);String username = rs.getString(2);System.out.println("username = " + username);int password = rs.getInt("password");System.out.println("password = " + password);}//7.关闭资源rs.close();st.close();connection.close();}
由于重复性代码太多于是可以抽取工具类进行代码改进(这里用到了结合properties文件实现)
public class JDBCUtils {private static String url = null;private static String name = null;private static String password = null;static {try {Properties properties = new Properties();InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.propertites");properties.load(in);Class.forName(properties.getProperty("driverclass"));url = properties.getProperty("url");name = properties.getProperty("name");password = properties.getProperty("password");} catch (Exception e) {e.printStackTrace();}}public static Connection getConn() {Connection connection = null;try {connection = DriverManager.getConnection(url, name, password);} catch (SQLException e) {e.printStackTrace();}return connection;}public static void close(Connection conn, ResultSet rs, Statement st) {if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}}if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}}if (st != null) {try {st.close();} catch (SQLException e) {e.printStackTrace();}}}}
4.使用PreparedStatement预处理对象
概述:PreparedStatement extends Statement
获取:Connection中的方法
PreparedStatement prepareStatement(String sql)
方法:
void setObject(int parameterIndex, Object x)//为?赋值
parameterIndex:指定第几个?
x:为?赋的值
int executeUpdate() //针对增删改操作的
ResultSet executeQuery() //针对于查询
具体使用场景:
public class Demo05PreparedStatement {public static void main(String[] args) throws SQLException {//1.创建scannner对象,键入用户和密码Scanner sc = new Scanner(System.in);System.out.println("请输入用户名:");String username = sc.nextLine();System.out.println("请输入密码:");String password = sc.nextLine();//2.连接数据库Connection conn = JDBCUtils.getConn();//3.准备sqlString sql = "select * from user where username = ? and password = ?";//4.获取执行平台PreparedStatement pst = conn.prepareStatement(sql);//5.为?赋值pst.setObject(1,username);pst.setObject(2,password);//6.执行ResultSet rs = pst.executeQuery();//7.直接判断结果集中有没有数据if(rs.next()){System.out.println("登录成功");}else{System.out.println("登陆失败");}}
}
5.PreparedStatement实现批量添加
public class Demo07Batch {public static void main(String[] args)throws Exception {//1.获取连接Connection conn = JDBCUtils.getConn();//2.准备sqlString sql = "insert into `user`(username,password) values (?,?)";//3.获取执行平台PreparedStatement pst = conn.prepareStatement(sql);//4.为?赋值//5.执行for (int i = 0; i < 10; i++) {pst.setObject(1,"张三");pst.setObject(2,"0000"+i);//将多条语句写入内存中pst.addBatch();}//将多条语句一起打包发送给mysql批量执行pst.executeBatch();//6.关流JDBCUtils.close(conn,null,pst);}
}
1.在设置完所有要添加的参数,调用PreparedStatement中的addBatch(),将SQL语句添加到PreparedStatement中
2.调用PreparedStatement中的executeBatch()方法批处理sql语句
6.改造JDBC工具类_结合Properties文件
driverclass=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/day01
name=root
password=root
static {try {Properties properties = new Properties();InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.propertites");//自动扫描resource下的文件(可以简单理解为扫描out路径下的配置文件) properties.load(in);//将流中的数据加载到集合中Class.forName(properties.getProperty("driverclass"));//获取Class对象url = properties.getProperty("url");name = properties.getProperty("name");password = properties.getProperty("password");} catch (Exception e) {e.printStackTrace();}
}
以上代码是利用了类加载器
ClassLoader classLoader = 当前类.class.getClassLoader()
InputStream in = classLoader.getResourceAsStream("文件名称");