欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

笔记-JavaWeb学习之旅4

程序员文章站 2022-05-15 12:31:47
JDBC: 概念:Java DataBase Connectivity Java 数据库连接,Java语言操作数据库 本质:其实是官方(sun公司)定义的一套操作所有关系型数据库的规则,即接口,各个数据库厂商去实现这套接口,提供数据库驱动jar包。我们可以使用这套接口编程,真正执行的代码是驱动jar ......

jdbc:

概念:java database connectivity java 数据库连接,java语言操作数据库

本质:其实是官方(sun公司)定义的一套操作所有关系型数据库的规则,即接口,各个数据库厂商去实现这套接口,提供数据库驱动jar包。我们可以使用这套接口编程,真正执行的代码是驱动jar包中的实现类(多态调用 fu f = new zi();)

package cn.itcast.jdbc;

import java.sql.connection;
import java.sql.drivermanager;
import java.sql.statement;

public class jdbcdemo1 {
    public static void main(string[] args) throws exception{
        //导入驱动jar包
        //加载driver类进内存,执行driver类的静态代码块,就可以注册驱动
        class.forname("com.mysql.jdbc.driver");
        //获取数据库连接对象
        // drivermanager驱动管理对象,
        //drivermanager是一个类
        // drivermanager类中的方法getconnection ,会返回一个connection对象
        //connection叫做数据库连接对象
        //connection是一个接口
        connection conn = drivermanager.getconnection("jdbc:mysql://localhost:3306/db3","root","12345");
        //定义一条sql语句
        string sql = "update emp set salary = 10000 where id = 1001";
        //drivermanager.getconnection返回的是一个connection对象,所以可以使用该对象conn调用需要的方法
        //该createstatement方法将会获得一个可以执行sql语句的对象
        //获取执行sql对象 statement
        statement stmt = conn.createstatement();
        //执行sql语句,返回值int代表着有多少行执行成功,受到影响
        int count = stmt.executeupdate(sql);
        system.out.println(count);
        stmt.close();
        conn.close();
    }
}

jdbc练习

package cn.itcast.jdbc;

import java.sql.connection;
import java.sql.drivermanager;
import java.sql.statement;

// 通过jdbc添加一条记录
public class jdbcdemo2 {
    public static void main(string[] args){
       statement stmt = null;
        connection conn = null;
        try{
        //1.注册驱动
        class.forname("com.mysql.jdbc.driver");
        //定义sql语句
        string sql = "insert into emp values(null,'张飞','男',5000,'2014-05-20',3)";
        //获取执行connection对象
            conn = drivermanager.getconnection("jdbc:mysql://localhost:3306/db2","root","12345");
            //获取执行sql的对象
           stmt = conn.createstatement();
            //执行sql
            stmt.executeupdate(sql);

        }catch(exception e){
            e.printstacktrace();
        }finally{
            //避免空指针异常
            if(stmt !=null){
                try{
                    stmt.close();
                }catch(exception e){
                    e.printstacktrace();
                }
            }else{
                system.out.println("发生null指针异常");
            }

            if(conn !=null){
                try {
                    conn.close();
                }catch(exception e){
                    e.printstacktrace();
                }
            }else{
                system.out.println("null指针异常");
            }

        }
    }
}
resultset:结果集对象,封装查询结果

常用方法有两个:

boolean next():游标向下移动一行,判断当前行是否是最后一行末尾

getxxx(参数) xxx代表数据类型,参数代表编号,编号从1开始,也可以代表列的名称

笔记-JavaWeb学习之旅4

package cn.itcast.jdbc;

import java.sql.connection;
import java.sql.drivermanager;
import java.sql.resultset;
import java.sql.statement;

import static javax.swing.text.html.parser.dtdconstants.name;

// 通过jdbc添加一条记录
public class jdbcdemo2 {
    public static void main(string[] args){
       statement stmt = null;
        connection conn = null;
        resultset rs = null;
        try{
        //1.注册驱动
        class.forname("com.mysql.jdbc.driver");
        //定义sql语句
        string sql = "select * from emp";
        //获取执行connection对象
            conn = drivermanager.getconnection("jdbc:mysql://localhost:3306/db2","root","12345");
            //获取执行sql的对象
           stmt = conn.createstatement();
            //执行sql
           rs = stmt.executequery(sql);
           //re.next的返回值是boolean类型
            while(rs.next()){
                //若为真,则获取数据
              int i= rs.getint(1);//这个参数是编号参数
                string s = rs.getstring("name"); //这个参数是一个列名称参数
                string s1 = rs.getstring("gender");
                system.out.println(i+" "+s1+" "+s);
            }

        }catch(exception e){
            e.printstacktrace();
        }finally{
            //避免空指针异常
            if(rs!=null){
                try{
                    stmt.close();
                }catch(exception e){
                    e.printstacktrace();
                }
            }else{
                system.out.println("发生null指针异常");
            }


        }
    }
}

笔记-JavaWeb学习之旅4

//定义一个方法,查询emp表的数据将其封装为对象,然后装载集合,返回
import java.util.date;

/**
 * 封装emp表数据的javabean
 */
public class emp {
    private int id;
    private string ename;
    private int job_id;
    private int mgr;
    private date joindate;
    private double salary;
    private double bonus;
    private int dept_id;


    public int getid() {
        return id;
    }

    public void setid(int id) {
        this.id = id;
    }

    public string getename() {
        return ename;
    }

    public void setename(string ename) {
        this.ename = ename;
    }

    public int getjob_id() {
        return job_id;
    }

    public void setjob_id(int job_id) {
        this.job_id = job_id;
    }

    public int getmgr() {
        return mgr;
    }

    public void setmgr(int mgr) {
        this.mgr = mgr;
    }

    public date getjoindate() {
        return joindate;
    }

    public void setjoindate(date joindate) {
        this.joindate = joindate;
    }

    public double getsalary() {
        return salary;
    }

    public void setsalary(double salary) {
        this.salary = salary;
    }


    public int getdept_id() {
        return dept_id;
    }

    public void setdept_id(int dept_id) {
        this.dept_id = dept_id;
    }


    public double getbonus() {
        return bonus;
    }

    public void setbonus(double bonus) {
        this.bonus = bonus;
    }


    @override
    public string tostring() {
        return "emp{" +
                "id=" + id +
                ", ename='" + ename + '\'' +
                ", job_id=" + job_id +
                ", mgr=" + mgr +
                ", joindate=" + joindate +
                ", salary=" + salary +
                ", bonus=" + bonus +
                ", dept_id=" + dept_id +
                '}';
    }
}
import java.sql.*;
import java.util.arraylist;
import java.util.list;

public class jdbcdemo3 {
   public static void main(string[] args){
    list<emp> list = new jdbcdemo3().findall();
       system.out.println(list);
   }
   public list<emp> findall() {
       connection conn = null;
       statement stat = null;
       resultset rs = null;
       list<emp> list = null;
       try {
           class.forname("com.mysql.jdbc.driver");
           //获取到connection对象
           conn = drivermanager.getconnection("jdbc:mysql:///db3", "root", "12345");
           //有了connecttion对象才会有statement执行sql语句的对象
           stat = conn.createstatement();
           //定义sql语句
           string sql = "select * from emp";
           //执行sql语句,返回的是结果集对象resultset()
           rs = stat.executequery(sql);
           //通过结果集对象的方法,可以获取到每一行的数据
           emp emp = null;
           list = new arraylist<emp>();
           while (rs.next()) {
               int id = rs.getint("id");
               string ename = rs.getstring("ename");
               int job_id = rs.getint("job_id");
               int mgr = rs.getint("mgr");
               date joindate = rs.getdate("joindate");
               double salary = rs.getdouble("salary");
               double bonus = rs.getdouble("bonus");
               int dept_id = rs.getint("dept_id");
               emp  = new emp();
               emp.setid(id);
               emp.setename(ename);
               emp.setjob_id(job_id);
               emp.setmgr(mgr);
               emp.setjoindate(joindate);
               emp.setsalary(salary);
               emp.setbonus(bonus);
               emp.setdept_id(dept_id);

               list.add(emp);
           }
       } catch (exception e) {
           e.printstacktrace();
       } finally {
           if (rs != null) {
               try {
                   rs.close();
               } catch (sqlexception e) {
                   e.printstacktrace();
               }
           }
           if (stat != null) {
               try {
                   rs.close();
               } catch (sqlexception e) {
                   e.printstacktrace();
               }
           }
           if (conn != null) {
               try {
                   rs.close();
               } catch (sqlexception e) {
                   e.printstacktrace();
               }
           }
       }
       return list;
   }
}

通过jdbcutils工具类改进代码

package cn.itcast.jdbc;


import java.io.filereader;
import java.io.ioexception;
import java.net.url;
import java.sql.*;
import java.util.properties;

public class jdbcutils {
        private static string url;
        private static string user;
        private static string password;
        private static string driver;
       static {

           try{
               properties pro = new properties();
               //可以通过字节码来获取类加载器
               classloader classloader = jdbcutils.class.getclassloader();
               //getresource方法可以找到sre文件夹下的配置文件
               url res = classloader.getresource("jdbc.properties");
                string path = res.getpath();
                pro.load(new filereader(path));
                url = pro.getproperty("url");
               user = pro.getproperty("user");
               password = pro.getproperty("password");
               driver = pro.getproperty("driver");
               class.forname(driver);
           }catch(ioexception e){
               e.printstacktrace();
           }catch(classnotfoundexception e){
               e.printstacktrace();
           }
       }
    //调用方法,返回connection对象
    public static connection getconnection() throws sqlexception{
            return drivermanager.getconnection(url,user,password);
    }

    //执行增删改需要释放statement和connection对象
    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();
            }
        }
    }

    //执行查询需要释放resultset,statement和connection对象
    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();
            }
        }
    }
}
package cn.itcast.jdbc;

import java.sql.*;
import java.util.arraylist;
import java.util.list;

public class jdbcdemo3 {
   public static void main(string[] args){
    list<emp> list = new jdbcdemo3().findall();
       system.out.println(list);
   }
   public list<emp> findall() {
       connection conn = null;
       statement stat = null;
       resultset rs = null;
       list<emp> list = null;
       try {
           conn = jdbcutils.getconnection();
           //有了connecttion对象才会有statement执行sql语句的对象
           stat = conn.createstatement();
           //定义sql语句
           string sql = "select * from emp";
           //执行sql语句,返回的是结果集对象resultset()
           rs = stat.executequery(sql);
           //通过结果集对象的方法,可以获取到每一行的数据
           emp emp = null;
           list = new arraylist<emp>();
           while (rs.next()) {
               int id = rs.getint("id");
               string ename = rs.getstring("ename");
               int job_id = rs.getint("job_id");
               int mgr = rs.getint("mgr");
               date joindate = rs.getdate("joindate");
               double salary = rs.getdouble("salary");
               double bonus = rs.getdouble("bonus");
               int dept_id = rs.getint("dept_id");
               emp  = new emp();
               emp.setid(id);
               emp.setename(ename);
               emp.setjob_id(job_id);
               emp.setmgr(mgr);
               emp.setjoindate(joindate);
               emp.setsalary(salary);
               emp.setbonus(bonus);
               emp.setdept_id(dept_id);

               list.add(emp);
           }
       } catch (exception e) {
           e.printstacktrace();
       } finally {
           jdbcutils.close(rs,stat,conn);
       }
       return list;
   }
}
jdbc练习_登录案例

需求:通过键盘录入用户名和密码,查看数据库,判断是否登录成功

create table user(
    id int primary key auto_increment,
    username varchar(32),
    password varchar(32)
);
insert into user values
(null,'zhangsan','123'),
(null,'lisi','234');
package cn.itcast.newjdbc;


import javax.xml.transform.result;
import java.sql.connection;
import java.sql.resultset;
import java.sql.sqlexception;
import java.sql.statement;
import java.util.scanner;

public class jdbcdemo5 {
    public static void main(string[] args) {
        scanner sc = new scanner(system.in);
        system.out.println("请输入用户名: ");
        string username = sc.nextline();
        system.out.println("请输入密码: ");
        string password  = sc.nextline();
        boolean flag = new jdbcdemo5().login(username,password);
        if(flag){
            system.out.println("登录成功");
        }else{
            system.out.println("用户名或密码错误");
        }
    }
    public boolean login(string username,string password){
        //若传入参数为null,自接返回false
        if(username == null|| password == null){
            return  false;
        }
        connection conn = null;
        statement stme = null;
        resultset rs = null;
        try{
            //获得数据库连接connection
            conn=  jdbcutils.getconnection();
            //写sql语句
            string sql = "select * from user where username = '"+username+"'and password='"+password+"'";
            //获得执行sql语句对象
            statement stmt = conn.createstatement();
            rs = stmt.executequery(sql);
            return rs.next();
        }catch (sqlexception e){
            e.printstacktrace();
        }
        return  false;
    }
}
jdbc管理事务:

事务:一个包含多个步骤的业务操作,如果这个业务被操作被事务管理,则这多个步骤要么同时成功,要么同时失败

使用connection对象来管理事务操作:

1.开启事务:在执行sql语句之前开启事务

2.提交事务,当所有sql都执行完提交事务

3,回滚事务,在catch中回滚事务

使用connection对象来管理事务

数据库连接池

概念:其实就是一个容器,存放数据库连接的容器

数据库连接池c3p0的使用

步骤:

  1. 导入jar包,jar包要单独一个目录
  2. 定义配置文件
  3. 创建核心对象
  4. 获取连接
package cn.itcast.datasourcejdbc;

import com.mchange.v2.c3p0.combopooleddatasource;

import javax.sql.datasource;
import java.sql.connection;
import java.sql.sqlexception;

public class c3p0demo1 {
    public static void main(string[] args) {
        //datasource是一个接口
        //创建数据库连接池对象
        //使用父类引用指向子类对象,多态
        datasource ds = new combopooleddatasource();
        //获取连接对象
        try {
            connection conn = ds.getconnection();
            system.out.println(conn);
        } catch (sqlexception e) {
            e.printstacktrace();
        }
    }
}

笔记-JavaWeb学习之旅4

笔记-JavaWeb学习之旅4