web开发日记-JDBC

有点高产了。。。


web开发日记-JDBC_第1张图片
jdbc编程流程
package com.webtest.jdbc;

import java.sql.*;

/**
 * Created by elijahliu on 2017/2/18.
 */
public class JDBCTest {

    public static void main(String[] args) {
        String sql = "SELECT * FROM tbl_user";
        //代表当前数据库链接
        Connection conn = null;
        //代表sql语句
        Statement st = null;

        //代表返回数据
        ResultSet rs = null;

        try {
//           Class.forName ("com.mysql.jdbc.Driver");//注册mysql驱动
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp_db","root","123456");//设置链接
            st = conn.createStatement();//代表statement套件
            rs = st.executeQuery(sql);//执行sql语句返回结果
            while (rs.next()) {//逐条读取数据,直到
                System.out.println(rs.getInt("id"));

                System.out.println(rs.getString("name"));
                System.out.println(rs.getString("password"));

            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                rs.close();
                st.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


    }
}

ps:必须在工程依赖中添加mysql-jdbc.jar的包。

基础操作 增删改查

package com.webtest.jdbc;

import java.sql.*;

/**
 * Created by elijahliu on 2017/2/18.
 */
public class JDBCTest {
    public static Connection getConnection() {
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp_db", "root", "123456");//设置链接

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;

    }
    public static void insert(){
        Connection conn = getConnection();
        String sql = "INSERT INTO tbl_user(name,password,email)"+"VALUES('Tom','123456','[email protected]')";
        try {
            Statement st = conn.createStatement();
            int cout = st.executeUpdate(sql);//运行插入sql语句,返回受影响条目数字 ,executeUpdate可以执行insert update delete ddl语句
            System.out.println("向用户表中插入了" + cout + " 条记录");
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


    }
    public static void update(){
        Connection conn = getConnection();
        String sql = "UPDATE tbl_user SET email = '[email protected]' WHERE name = Tom";
        try {
            Statement st = conn.createStatement();
            int cout = st.executeUpdate(sql);//运行插入sql语句,返回受影响条目数字 ,executeUpdate可以执行insert update delete ddl语句
            System.out.println("向用户表中更新了" + cout + " 条记录");
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
    public static void delete(){
        Connection conn = getConnection();
        String sql = "DELETE FROM tbl_user WHERE name = 'Tom'";
        try {
            Statement st = conn.createStatement();
            int cout = st.executeUpdate(sql);//运行插入sql语句,返回受影响条目数字 ,executeUpdate可以执行insert update delete ddl语句
            System.out.println("向用户表中删除了" + cout + " 条记录");
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }


    public static void main(String[] args) {
        String sql = "SELECT * FROM tbl_user";
        //代表当前数据库链接
        Connection conn = null;
        //代表sql语句
        Statement st = null;

        //代表返回数据
        ResultSet rs = null;

        try {
//           Class.forName ("com.mysql.jdbc.Driver");//注册mysql驱动
            conn = getConnection();
            st = conn.createStatement();//代表statement套件
            rs = st.executeQuery(sql);//执行sql语句返回结果
            while (rs.next()) {//逐条读取数据,直到
                System.out.println(rs.getInt("id"));

                System.out.println(rs.getString("name"));
                System.out.println(rs.getString("password"));

            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                rs.close();
                st.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        //插
        insert();
        update();
        delete();
    }
}

JDBC编程之事务处理

事务

在多用户对同一数据进行同时操作时,对数据的更改会出现不同步的问题,破坏数据的一致性。而事务就是进行并发控制的基本单位,事务是一个操作序列,这些操作要么都执行要么都不执行,是一个不可分割的工作单位。比如银行转账的工作,一个账户扣钱,一个账户加钱,要么都执行,要么都不执行。在每个事务结束时都能保证数据的一致性。

对于coder来说,事务也可以说是一组连续的sql操作,要么对数据进行永久性的更改,要么不更改。

事务的特征

原子性

事务中包含的操作被看作一个逻辑单元,要么全部成功,要么全部失败。事务的所有元素作为一个整体提交或回滚。事务的操作是不可分割的。

一致性

事务开始之前和事务结束之后,数据库都处于一致性状态,数据库完整性没有被破坏。

隔离性

对数据库修改的各个事务是相互隔离的,独立的,不能由一个事务而去影响其他事务。

持久性

是说,事务完成之后,对于数据的影响是永久的,即使系统出现故障也会一直保留,真实的修改了数据库。

事务的语句

  • 开始事务:BEGIN TRANSACTION
  • 提交事务:COMMIT TRANSACTION
  • 回滚事务: ROLLBACK TRANSACTION

例子:添加id为10的一条成员记录,再添加一条id为1的地址记录,因为id为1的条目已经存在,则会发生主键冲突异常。所以在main中使用conn.rollback进行回滚操作。

package com.webtest.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by elijahliu on 2017/2/18.
 */
public class TransactionTest {
    public static Connection getConnection() {
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp_db", "root", "123456");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public static void insertUserData(Connection conn) throws SQLException {
        String sql = "INSERT INTO tbl_user(id,name,password,email)" +
                "VALUES(10,'Tom','123456','[email protected]')";
        Statement st = null;

        st = conn.createStatement();
        int count = st.executeUpdate(sql);
        System.out.println("向用户表中插入了" + count + "条记录");
        //在这里的最后不需要进行conn.close(),在main方法中一起关掉就好

    }

    public static void insertAddressData(Connection conn) throws SQLException {
        String sql = "INSERT INTO tbl_address(id,city,country,user_id)" +
                "VALUES(1,'shanghai''china','10')";

        Statement st = conn.createStatement();
        int count = st.executeUpdate(sql);
        System.out.println("向地址表中插入了" + count + "条记录");

        //在这里的最后不需要进行conn.close(),在main方法中一起关掉就好


    }

    public static void main(String[] args) {
        Connection conn = null;
        try {
            conn = getConnection();
            conn.setAutoCommit(false);//禁止事务的自动提交

            insertUserData(conn);
            insertAddressData(conn);

            conn.commit();//提交事务
        } catch (SQLException e) {
            System.out.println("===============捕获到异常================");
            e.printStackTrace();
            try {
                conn.rollback();
                System.out.println("===========事务回回滚成功===============");
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        } finally {
            try {
                if (conn != null) {

                    conn.close();

                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

web开发日记-JDBC_第2张图片
用户表
web开发日记-JDBC_第3张图片
地址表

JDBC之程序优化

前面的程序都是在程序中“硬配置”,其实可以创建一个配置文件来进行存储,也就是.properties文件。
首先建立dbconfig.properties

driver=com.mysql.jdbc.Driver
dburl=jdbc\:mysql\://localhost\:3306/jsp_db
user=root
password=123456

ConnectionFactory.java

package com.webtest.util;

import com.mysql.jdbc.Driver;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Created by elijahliu on 2017/2/18.
 */
public class ConnectionFactory {
    private static String driver;
    private static String dburl;
    private static String user;
    private static String password;

    private Connection conn;

    private static final ConnectionFactory factory = new ConnectionFactory();//声明一个这个类的成员变量

    static {
        Properties prop = new Properties();//定义一个properties,适用于储存文件中的键值对的
        try {
            InputStream in = ConnectionFactory.class.getClassLoader()
                    .getResourceAsStream("dbconfig.properties");
            prop.load(in);
        } catch (Exception e) {
            System.out.println("============配置文件读取错误=============");

        }
        driver = prop.getProperty("driver");
        dburl = prop.getProperty("dburl");
        user = prop.getProperty("user");
        password = prop.getProperty("password");

    }

    private ConnectionFactory(){

    }
    public static ConnectionFactory getInstance(){
        return factory;
    }
    public Connection makeConnection(){
        try {
            conn = DriverManager.getConnection(dburl, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
}

ConnectionFactory.java

package com.webtest.util;

import com.mysql.jdbc.Driver;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Created by elijahliu on 2017/2/18.
 */
public class ConnectionFactory {
    private static String driver;
    private static String dburl;
    private static String user;
    private static String password;

    private Connection conn;

    private static final ConnectionFactory factory = new ConnectionFactory();//声明一个这个类的成员变量

    static {
        Properties prop = new Properties();//定义一个properties,适用于储存文件中的键值对的
        try {
            InputStream in = ConnectionFactory.class.getClassLoader()
                    .getResourceAsStream("dbconfig.properties");
            prop.load(in);
        } catch (Exception e) {
            System.out.println("============配置文件读取错误=============");

        }
        driver = prop.getProperty("driver");
        dburl = prop.getProperty("dburl");
        user = prop.getProperty("user");
        password = prop.getProperty("password");

    }

    private ConnectionFactory(){

    }
    public static ConnectionFactory getInstance(){//在这里使用了单例模式,只允许有一个Connection链接
        return factory;
    }
    public Connection makeConnection(){
        try {
            conn = DriverManager.getConnection(dburl, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
}

DTO类

data transfer object数据传输对象,用于远程调用等对象需要大量调用的地方。
创建三个DTO类

IdEntity.java

package com.webtest.entity;

/**
 * Created by elijahliu on 2017/2/18.
 */
public abstract class IdEntity {
    protected long id;
    public long getId(){
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

}
//此方法相当于核心抽象类

Address.java

package com.webtest.entity;

/**
 * Created by elijahliu on 2017/2/18.
 */
public class Address extends IdEntity {
    private String city;
    private String country;
    private String userId;

    @Override
    public String toString() {
        return "Address{" +
                "city='" + city + '\'' +
                ", country='" + country + '\'' +
                ", userId='" + userId + '\'' +
                '}';
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }
}

User.java

package com.webtest.entity;

import com.sun.javafx.geom.transform.Identity;

/**
 * Created by elijahliu on 2017/2/18.
 */
public class User extends IdEntity {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmaill() {
        return emaill;
    }

    public void setEmaill(String emaill) {
        this.emaill = emaill;
    }

    private String password;
    private String emaill;

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", password='" + password + '\'' +
                ", emaill='" + emaill + '\'' +
                '}';
    }
}

DAO类

data access object数据访问对象,主要是用来封装数据库中的表,将数据库中的数据转化为DTO类。

创建UserDao、 dao/impl/UserDaoimpl、
com.webtest.Test/UserDaoTest.java三个文件。

UserDao.interface

package com.webtest.dao;

import com.webtest.entity.User;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created by elijahliu on 2017/2/18.
 */
public interface UserDao {
    public void save(Connection conn, User user) throws SQLException;
    public void update(Connection conn,Long id,User user) throws SQLException;

    public void delete(Connection conn, User user) throws SQLException;

    //需要编写相应的实现,这是典型的面向接口的编程,接口只定义外观和行为
}

UserDaoimpl.java (UserDao的实现类)

package com.webtest.dao.impl;

import com.webtest.dao.UserDao;
import com.webtest.entity.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Created by elijahliu on 2017/2/18.
 */
public class UserDaoimpl implements UserDao {

    /*
    * 保存用户信息
    * */

    @Override
    public void save(Connection conn, User user) throws SQLException {
        PreparedStatement ps = conn.prepareCall("INSERT INTO  tbl_user(name,password,email) VALUES (?,?,?)");
        ps.setString(1,user.getName());
        ps.setString(2, user.getPassword());
        ps.setString(3,user.getEmaill());
        ps.execute();

        //这里使用的PreparedStatement是jdbc用来执行的sql查询语句的api之一,用于执行参数化的查询
        //?是占位符,下面的setString方法,是用来替换占位符的。将user对象中的数据填补到sql语句中
        //从而进行正确的查询,所以最后ps.execute() 执行。
    }

    /*
    *
    * 根据指定的id更新用户信息
    * */


    @Override
    public void update(Connection conn, Long id, User user) throws SQLException {

        PreparedStatement ps = conn.prepareStatement("UPDATE tbl_user SET name=?,password=?,email=? WHERE id=?");

        ps.setString(1, user.getName());
        ps.setString(2, user.getPassword());
        ps.setString(3, user.getEmaill());
        ps.setLong(4, id);

        ps.execute();

    }

    /*
    *
    * 删除制定的用户信息
    *
    * */

    @Override
    public void delete(Connection conn, User user) throws SQLException {
        PreparedStatement ps = conn.prepareStatement("DELETE FROM tbl_user WHERE id=?");
        ps.setLong(1, user.getId());
        ps.execute();


    }
}

UserDaoTest.java

package com.webtest.Test;

import com.webtest.dao.UserDao;
import com.webtest.dao.impl.UserDaoimpl;
import com.webtest.entity.User;
import com.webtest.util.ConnectionFactory;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created by elijahliu on 2017/2/18.
 */
public class UserDaoTest {
    public static void main(String[] args) {
        Connection conn = null;
        try {
            conn = ConnectionFactory.getInstance().makeConnection();

            conn.setAutoCommit(false);//关闭连接事务的自动提交

            UserDao userDao = new UserDaoimpl();
            User tom = new User();
            tom.setName("Tom");
            tom.setPassword("123456");
            tom.setEmaill("[email protected]");

            userDao.save(conn,tom); //调用持久层存储

            conn.commit();//事务提交
        } catch (SQLException e) {
            try {
                conn.rollback();//存在异常则进行事务回滚
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }

    }
}

你可能感兴趣的:(web开发日记-JDBC)