学习日常笔记<day17>jdbc基础
1.jdbc入门
1.1.jdbc定义
使用java代码发送sql语句的技术就是jdbc技术
1.2.使用jdbc发送sql前提
需要登录数据库服务器(数据库的IP地址,端口,数据库用户名,密码)
/**
* jdbc连接数据库
* @author APPle
*
*/
public class Demo1 {
//连接数据库的URL
private String url = "jdbc:mysql://localhost:3306/day17";
// jdbc协议:数据库子协议:主机:端口/连接的数据库 //
private String user = "root";//用户名
private String password = "root";//密码
/**
* 第一种方法
* @throws Exception
*/
@Test
public void test1() throws Exception{
//1.创建驱动程序类对象
Driver driver = new com.mysql.jdbc.Driver(); //新版本
//Driver driver = new org.gjt.mm.mysql.Driver(); //旧版本
//设置用户名和密码
Properties props = new Properties();
props.setProperty("user", user);
props.setProperty("password", password);
//2.连接数据库,返回连接对象
Connection conn = driver.connect(url, props);
System.out.println(conn);
}
/**
* 使用驱动管理器类连接数据库(注册了两次,没必要)
* @throws Exception
*/
public void test2() throws Exception{
Driver driver = new com.mysql.jdbc.Driver();
//Driver driver2 = new com.oracle.jdbc.Driver();
//1.注册驱动程序(可以注册多个驱动程序)
DriverManager.registerDriver(driver);
//DriverManager.registerDriver(driver2);
//2.连接到具体的数据库
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
/**
* (推荐使用这种方式连接数据库)
* 推荐使用加载驱动程序类 来 注册驱动程序
* @throws Exception
*/
public void test3() throws Exception{
//Driver driver = new com.mysql.jdbc.Driver();
//通过得到字节码对象的方式加载静态代码块,从而注册驱动程序
Class.forName("com.mysql.jdbc.Driver");
//Driver driver2 = new com.oracle.jdbc.Driver();
//1.注册驱动程序(可以注册多个驱动程序)
//DriverManager.registerDriver(driver);
//DriverManager.registerDriver(driver2);
//2.连接到具体的数据库
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
}
1.3.JDBC接口的核心API
|-Driver接口: 表示java驱动程序接口。所有的具体的数据库厂商要来实现此接口。
|- connect(url, properties): 连接数据库的方法。
url: 连接数据库的URL
URL语法: jdbc协议:数据库子协议://主机:端口/数据库
user: 数据库的用户名
password: 数据库用户密码
|-DriverManager类: 驱动管理器类,用于管理所有注册的驱动程序
|-registerDriver(driver) : 注册驱动类对象
|-Connection getConnection(url,user,password); 获取连接对象
|-Connection接口: 表示java程序和数据库的连接对象。
|- Statement createStatement() : 创建Statement对象
|- PreparedStatement prepareStatement(String sql) 创建PreparedStatement对象
|- CallableStatement prepareCall(String sql) 创建CallableStatement对象
|-Statement接口: 用于执行静态的sql语句
|- int executeUpdate(String sql) : 执行静态的更新sql语句(DDL,DML)
|- ResultSet executeQuery(String sql) :执行的静态的查询sql语句(DQL)
|-PreparedStatement接口:用于执行预编译sql语句
|- int executeUpdate() : 执行预编译的更新sql语句(DDL,DML)
|-ResultSet executeQuery() : 执行预编译的查询sql语句(DQL) |-CallableStatement接口:用于执行存储过程的sql语句(call xxx)
|-ResultSet executeQuery() : 调用存储过程的方法
|-ResultSet接口:用于封装查询出来的数据
|- boolean next() : 将光标移动到下一行
|-getXX() : 获取列的值
2.使用Stetement执行sql语句
2.1执行DDL语句
/**
* 执行DDL语句(创建表)
*/
@Test
public void test1(){
Statement stmt = null;
Connection conn = null;
try {
//1.驱动注册程序
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接对象
conn = DriverManager.getConnection(url, user, password);
//3.创建Statement
stmt = conn.createStatement();
//4.准备sql
String sql = "CREATE TABLE student(id INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(20),gender VARCHAR(2))";
//5.发送sql语句,执行sql语句,得到返回结果
int count = stmt.executeUpdate(sql);
//6.输出
System.out.println("影响了"+count+"行!");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally{
//7.关闭连接(顺序:后打开的先关闭)
if(stmt!=null)
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
if(conn!=null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
2.2执行DML语句
private String url = "jdbc:mysql://localhost:3306/day17";
private String user = "root";
private String password = "root";
2.2.1增加
public void testInsert(){
    Connection conn = null;
    Statement stmt = null;
    try {
        //通过工具类获取连接对象
        conn = JdbcUtil.getConnection();
        //3.创建Statement对象
        stmt = conn.createStatement();
        //4.sql语句
        String sql = "INSERT INTO student(NAME,gender) VALUES('李四','女')";
        //5.执行sql
        int count = stmt.executeUpdate(sql);
        System.out.println("影响了"+count+"行");
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally{
        //关闭资源
        /*if(stmt!=null)
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        if(conn!=null)
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }*/
        JdbcUtil.close(conn, stmt);
    }
}
2.2.2修改
public void testUpdate(){
    Connection conn = null;
    Statement stmt = null;
    //模拟用户输入
    String name = "陈六";
    int id = 3;
    try {
        /*//1.注册驱动
        Class.forName("com.mysql.jdbc.Driver");
            //2.获取连接对象
        conn = DriverManager.getConnection(url, user, password);*/
        //通过工具类获取连接对象
        conn = JdbcUtil.getConnection();
        //3.创建Statement对象
                stmt = conn.createStatement();
        //4.sql语句
                String sql = "UPDATE student SET NAME='"+name+"' WHERE id="+id+"";
        System.out.println(sql);
        //5.执行sql
        int count = stmt.executeUpdate(sql);
        System.out.println("影响了"+count+"行");
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally{
        //关闭资源
                /*if(stmt!=null)
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        if(conn!=null)
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }*/
        JdbcUtil.close(conn, stmt);
    }
}            
2.2.3删除
public void testDelete(){
    Connection conn = null;
    Statement stmt = null;
    //模拟用户输入
    int id = 3;
    try {
        /*//1.注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2.获取连接对象
        conn = DriverManager.getConnection(url, user, password);*/
        //通过工具类获取连接对象
        conn = JdbcUtil.getConnection();
        //3.创建Statement对象
        stmt = conn.createStatement();
        //4.sql语句
        String sql = "DELETE FROM student WHERE id="+id+"";
        System.out.println(sql);
        //5.执行sql
        int count = stmt.executeUpdate(sql);
        System.out.println("影响了"+count+"行");
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally{
        //关闭资源
        /*if(stmt!=null)
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        if(conn!=null)
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
                }*/
        JdbcUtil.close(conn, stmt);
    }
}
2.3执行DQL语句
/**
* 使用Statement执行DQL语句(查询操作)
* @author APPle
*/
public class Demo3 { @Test
public void test1(){
Connection conn = null;
Statement stmt = null;
try{
//获取连接
conn = JdbcUtil.getConnection();
//创建Statement
stmt = conn.createStatement();
//准备sql
String sql = "SELECT * FROM student";
//执行sql
ResultSet rs = stmt.executeQuery(sql); //移动光标
/*boolean flag = rs.next(); flag = rs.next();
flag = rs.next();
if(flag){
//取出列值
//索引
int id = rs.getInt(1);
String name = rs.getString(2);
String gender = rs.getString(3);
System.out.println(id+","+name+","+gender); //列名称
int id = rs.getInt("id");
String name = rs.getString("name");
String gender = rs.getString("gender");
System.out.println(id+","+name+","+gender);
}*/ //遍历结果
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String gender = rs.getString("gender");
System.out.println(id+","+name+","+gender);
} }catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e);
}finally{
JdbcUtil.close(conn, stmt);
}
}
}
3.使用PreparedStetement执行sql语句
3.1增加
public void testInsert() {
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            //1.获取连接
            conn = JdbcUtil.getConnection();
            //2.准备预编译的sql
            String sql = "INSERT INTO student(NAME,gender) VALUES(?,?)"; //?表示一个参数的占位符
            //3.执行预编译sql语句(检查语法)
            stmt = conn.prepareStatement(sql);
            //4.设置参数值
            /**
             * 参数一: 参数位置  从1开始
             */
            stmt.setString(1, "李四");
            stmt.setString(2, "男");
            //5.发送参数,执行sql
            int count = stmt.executeUpdate();
            System.out.println("影响了"+count+"行");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            JdbcUtil.close(conn, stmt);
        }
    }
3.2修改
public void testUpdate() {
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            //1.获取连接
            conn = JdbcUtil.getConnection();
            //2.准备预编译的sql
            String sql = "UPDATE student SET NAME=? WHERE id=?"; //?表示一个参数的占位符
            //3.执行预编译sql语句(检查语法)
            stmt = conn.prepareStatement(sql);
            //4.设置参数值
            /**
             * 参数一: 参数位置  从1开始
             */
            stmt.setString(1, "王五");
            stmt.setInt(2, 9);
            //5.发送参数,执行sql
            int count = stmt.executeUpdate();
            System.out.println("影响了"+count+"行");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            JdbcUtil.close(conn, stmt);
        }
    }
3.3删除
public void testDelete() {
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            //1.获取连接
            conn = JdbcUtil.getConnection();
            //2.准备预编译的sql
            String sql = "DELETE FROM student WHERE id=?"; //?表示一个参数的占位符
            //3.执行预编译sql语句(检查语法)
            stmt = conn.prepareStatement(sql);
            //4.设置参数值
            /**
             * 参数一: 参数位置  从1开始
             */
            stmt.setInt(1, 9);
            //5.发送参数,执行sql
            int count = stmt.executeUpdate();
            System.out.println("影响了"+count+"行");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            JdbcUtil.close(conn, stmt);
        }
    }
3.4查询
public void testQuery() {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            //1.获取连接
            conn = JdbcUtil.getConnection();
            //2.准备预编译的sql
            String sql = "SELECT * FROM student"; 
            //3.预编译
            stmt = conn.prepareStatement(sql);
            //4.执行sql
            rs = stmt.executeQuery();
            //5.遍历rs
            while(rs.next()){
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String gender = rs.getString("gender");
                System.out.println(id+","+name+","+gender);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            //关闭资源
            JdbcUtil.close(conn,stmt,rs);
        }
    }
PreparedStatement vs Statment
1)语法不同:PreparedStatement可以使用预编译的sql,而Statment只能使用静态的sql
2)效率不同: PreparedStatement可以使用sql缓存区,效率比Statment高
3)安全性不同: PreparedStatement可以有效防止sql注入,而Statment不能防止sql注入。
推荐使用PreparedStatement
4.使用CallableStatement执行存储过程
4.1带有输入参数的存储过程
public void test1(){
        Connection conn = null;
        CallableStatement stmt = null;
        ResultSet rs = null;
        try {
            //获取连接
            conn = JdbcUtil.getConnection();
            //准备sql
            String sql = "CALL pro_findById(?)"; //可以执行预编译的sql
            //预编译
            stmt = conn.prepareCall(sql);
            //设置输入参数
            stmt.setInt(1, 6);
            //发送参数
            rs = stmt.executeQuery(); //注意: 所有调用存储过程的sql语句都是使用executeQuery方法执行!!!
            //遍历结果
            while(rs.next()){
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String gender = rs.getString("gender");
                System.out.println(id+","+name+","+gender);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            JdbcUtil.close(conn, stmt ,rs);
        }
    }
4.2带有输出参数的存储过程
public void test2(){
        Connection conn = null;
        CallableStatement stmt = null;
        ResultSet rs = null;
        try {
            //获取连接
            conn = JdbcUtil.getConnection();
            //准备sql
            String sql = "CALL pro_findById2(?,?)"; //第一个?是输入参数,第二个?是输出参数
            //预编译
            stmt = conn.prepareCall(sql);
            //设置输入参数
            stmt.setInt(1, 6);
            //设置输出参数(注册输出参数)
            /**
             * 参数一: 参数位置
             * 参数二: 存储过程中的输出参数的jdbc类型    VARCHAR(20)
             */
            stmt.registerOutParameter(2, java.sql.Types.VARCHAR);
            //发送参数,执行
            stmt.executeQuery(); //结果不是返回到结果集中,而是返回到输出参数中
            //得到输出参数的值
            /**
             * 索引值: 预编译sql中的输出参数的位置
             */
            String result = stmt.getString(2); //getXX方法专门用于获取存储过程中的输出参数
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            JdbcUtil.close(conn, stmt ,rs);
        }
    }
学习日常笔记<day17>jdbc基础的更多相关文章
- 学习日常笔记<day15>mysql基础
		
1.数据库入门 1.1数据库软件 数据库:俗称数据的仓库,方便管理数据的软件(或程序) 1.2市面上数据库软件 Oracle,甲骨文公司的产品. 当前最流行应用最广泛的数据库软件.和java语言兼容非 ...
 - 学习日常笔记<day12>jsp基础
		
1.Jsp基础 1.1Jsp引入 Servlet的作用:用java语言开发动态资源的技术 Jsp的作用:用java语言(+html语言)开发动态资源的技术 jsp就是servlet 1.2Jsp的特点 ...
 - Scala学习教程笔记一之基础语法,条件控制,循环控制,函数,数组,集合
		
前言:Scala的安装教程:http://www.cnblogs.com/biehongli/p/8065679.html 1:Scala之基础语法学习笔记: :声明val变量:可以使用val来声明变 ...
 - 超全面的JavaWeb笔记day17<JDBC>
		
1.JDBC的原理 是由JavaEE提供的连接数据库的规范 需要由各大数据库的厂商提供对JDBC的实现类 2.四大核心类 3.四大参数 driverClassName url username pas ...
 - 学习日常笔记<day16>mysql加强
		
1.数据约束 1.1什么是数据约束 对用户操作表的数据进行约束 1.2 默认值 作用:当永辉对使用默认值的字段不插入值的时候,就使用默认值 注意: 1)对默认值字段插入null是可以的 2)对默认值字 ...
 - 学习日常笔记<day13>jsp加强
		
1.jsp的内置对象(重点) 1.1什么是内置对象? 在jsp开发中,会频繁使用到一些现象 例如HttpSession,ServletContext,ServletContext,HttpServle ...
 - 学习日常笔记<day10>servlet编程
		
1 如何开发一个Servlet 1.1 步骤: 1)编写java类,继承HttpServlet类 2)重新doGet和doPost方法 3)Servlet程序交给tomcat服务器运行!! 3.1 s ...
 - 学习日常笔记<day14>自定义标签
		
1自定义标签 1.1第一个自定义标签开发步骤 1)编写一个普通的java类,继承SimpleTagSupport类,叫标签处理器类 /** * 标签处理器类 * @author APPle * 1)继 ...
 - 学习日常笔记<day11>cookie及session
		
1.会话管理 1.1会话管理定义 会话管理:管理浏览器客户端和服务端之间的会话过程中产生的会话数据 域对象:实现资源之间的数据共享 request 域对象 context 域对象 1.2.会话技术 C ...
 
随机推荐
- 【HEVC简介】High Level Syntax
			
参考文献:见<High Efficiency Video Coding (HEVC)>High Level Syntax章节 <HEVC标准介绍.HEVC帧间预测论文笔记>系列 ...
 - Windows程序设计1(工具、编码、窗口)
			
一.几个常用小工具: 1. 编译器:CL.EXE 将源文件转变为目标文件(汇编语言). CL.EXE /c xxx.c 或 xx.cpp cl.exe -? 显示cl帮助 cl.exe ...
 - 深度剖析 MySQL 事务隔离
			
概述 今天主要分享下MySQL事务隔离级别的实现原理,因为只有InnoDB支持事务,所以这里的事务隔离级别是指InnoDB下的事务隔离级别. 隔离级别 读未提交:一个事务可以读取到另一个事务未提交的修 ...
 - TebsorFlow低阶API(五)—— 保存和恢复
			
简介 tf.train.Saver 类提供了保存和恢复模型的方法.通过 tf.saved_model.simple_save 函数可以轻松地保存适合投入使用的模型.Estimator会自动保存和恢复 ...
 - 暑假集训 || 区间DP
			
区间DP 经典石子合并问题V1 复杂度 On3 int a[SZ], sum[SZ], f[SZ][SZ]; int main() { int n; scanf("%d", ...
 - 点击按钮打开一个新的窗口 关键词(Intent, setData , putExtra , startActivity |Bundle)
			
M3U8_Video_demo 项目 //------------------ 创建发送private void playVideo(String source, String title) { if ...
 - web前端中的一些注释表达法
			
1.HTML注释 <!--注释的内容--> 注释的地方(根据个人习惯可能有所不同): 结束标签的后面,这一切都是为了程序在嵌套的时候更加方便.明了,如: <div class=&qu ...
 - 我的MySql掉队了
			
本来今天高高兴兴,突然: raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)&qu ...
 - 条款33:避免遮掩继承而来的名称(Avoiding hiding inherited names)
			
NOTE: 1.derived classes 内的名称会遮掩base classes内的名称.在public继承下从来没有人希望如此. 2.为了让被遮掩的名称再见天日,可使用using 声明方式或转 ...
 - 【02】sass更新的方法
			
[02]更新的方法 gem install sass **