jdbc---javaweb-day1


  • 下载mysql驱动,在myeclipse新建的java项目目录下中新建libs,将驱动拷贝于此。

  • 可以使用mysql桌面工具打开mysql服务,或者利用其它的方式(命令安装打开Mysql服务)。

  • 打开数据库添加数据库和数据表


接下来就是在myeclipse中写代码了。

package com.lgq.mytestjdbc;

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

public class MyJdbc {

    public static Connection getConnect() {

        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/webtest","root","root");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return conn;
    }
    //插入
    public static void insert() {

        Connection conn = getConnect();

        try {
            String insertSql = "insert into students(name,age,class)"+
                    "values('小刘','18','1')";
            Statement st = conn.createStatement();
            int count = st.executeUpdate(insertSql);
            System.out.println("插入了"+count+"条数据。");

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

    }


    public static void main(String[] args) {

        insert();
    }

}

运行,查询数据库字段确实有增加一条数据。至此,jdbc将项目和mysql数据库已经连接上了。


但是事务的提交具有一致性等特性。如果一个事务处理插入两条数据,要么都插入,要么都不插入。所以代码修改如下:
package com.lgq.mytestjdbc;

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

public class TransactionTest {

    public static Connection getConnection() {
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/webtest", "root", "root");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    public static void insertData(Connection conn) throws SQLException {

        String insertSql = "insert into students(name,age,class)" + "values('小刘','18','1')";
        Statement st = conn.createStatement();
        int count = st.executeUpdate(insertSql);
        System.out.println("插入了" + count + "条数据。");

    }

    public static void updateGrade(Connection conn) throws SQLException {

        String insertSql = "insert into grade(id,class,size)" + "values('2','2','22')";
        Statement st = conn.createStatement();
        int count = st.executeUpdate(insertSql);
        System.out.println("插入了" + count + "条数据。");

    }

    public static void main(String[] args) {

        Connection conn = null;

        try {
            conn= getConnection();
            conn.setAutoCommit(false);//设置不自动提交事务


            insertData(conn);
            updateGrade(conn);

            conn.commit();

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

            try {
                System.out.println(" 事务回滚成功 !");
                conn.rollback(); //异常,事务回滚,事务的一致性
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }finally {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e3) {
                e3.printStackTrace();
            }
        }

    }

}

但是数据库的参数强硬写在代码中,总感觉维护性很差。所以,可以通过在sec主目录下新建一个dbconfig.properties,来数据库常量。
driver=com.mysql.jdbc.Driver
dburl=jdbc\:mysql\://127.0.0.1\:3306/webtest
user=root
password=root

这样就可以建立一个数据库连接工厂类来连接数据库。

package com.lgq.utils;

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

/**
 * 该类的目的是优化连接数据库
 * 静态代码块读取配置信息内容
 * 将连接数据库的属性参数放到配置文件中
 * 单例使用连接工厂类
 */
public class ConnectionFactory {

    private static String driver = null;
    private static String dburl = null;
    private static String user = null;
    private static String password = null;

    private Connection conn;

    static{
        Properties properties = new Properties();

        try {
            InputStream is = ConnectionFactory.class.getClassLoader()
                    .getResourceAsStream("dbconfig.properties");
            properties.load(is);
        } catch (Exception e) {
            System.out.println("读取配置信息错误!");
            e.printStackTrace();
        }
        //加载配置信息
        driver = properties.getProperty("driver");
        dburl = properties.getProperty("dburl");
        user = properties.getProperty("user");
        password = properties.getProperty("password");
    }

    //单例模式
    private ConnectionFactory() {       
    }

    public static ConnectionFactory getInstanceConnection(){
        return SingleHolder.connectionFactory;
    }
    private static class SingleHolder{
        static final ConnectionFactory connectionFactory = new ConnectionFactory();
    }

    public  Connection getConnection() {
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(dburl,user,password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }
}

数据库连接上了,对于数据库的增删改查,就可以用DTO(数据传输对象(Data Transfer Object)),实体类entity就不列出代码了。实体类中成员变量对应数据库的字段,提供set,get方法。

DAO(Data Access Object)是一个数据访问接口,数据访问:顾名思义就是与数据库打交道。夹在业务逻辑与数据库资源中间。

  • 根据实体类,新建数据访问接口。
package com.lgq.dao;

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

import com.lgq.entity.Students;

public interface StudentsDao {

    public void insert(Connection conn, Students stu) throws SQLException;

    public void update(Connection conn, long id, Students stu) throws SQLException;

    public void delete(Connection conn, Students stu) throws SQLException;

}

所以说,java很多都是面向接口编程的。接口有利于项目工程代码的可维护性和可扩展性。只要接口不变,实现接口的方法可以任意实现。新建实现接口业务的类。

package com.lgq.dao.impl;

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

import com.lgq.dao.StudentsDao;
import com.lgq.entity.Students;

public class StudentsDaoImpl implements StudentsDao{

    /**
     * 保存信息
     */
    @Override
    public void insert(Connection conn, Students stu) throws SQLException {
        PreparedStatement ps = conn.prepareCall("insert into students(name,age,banji) values (?,?,?)");
        //索引从1开始
        ps.setString(1, stu.getName());
        ps.setInt(2, stu.getAge());
        ps.setInt(3, stu.getBanji());
        ps.execute();

    }

    /**
     * 根据id修改信息
     */
    @Override
    public void update(Connection conn, long id, Students stu) throws SQLException {
        String sql = "update students set name = ?,age = ?,banji = ? where id = ? ";
        PreparedStatement ps = conn.prepareStatement(sql);

        ps.setString(1, stu.getName());
        ps.setInt(2, stu.getAge());
        ps.setInt(3, stu.getBanji());
        ps.setLong(4, stu.getId());
        ps.execute();

    }

    /**
     * 根据id删除信息
     */
    @Override
    public void delete(Connection conn, Students stu) throws SQLException {
        String sql = "delete from students where id = ?";
        PreparedStatement ps = conn.prepareStatement(sql);

        ps.setLong(1, stu.getId());
        ps.execute();

    }

}

至此数据库连接的后台操作就差不多完成了,自己可以新建一个test类,对数据经常操作。

package com.lgq.test;

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

import com.lgq.dao.StudentsDao;
import com.lgq.dao.impl.StudentsDaoImpl;
import com.lgq.entity.Students;
import com.lgq.utils.ConnectionFactory;

public class StudentsDaoTest {

    public static void main(String[] args) {
        Connection conn = null; 
        try {
            ConnectionFactory cf = ConnectionFactory.getInstanceConnection();
            conn = cf.getConnection();
            conn.setAutoCommit(false);

            StudentsDao studentsDao = new StudentsDaoImpl();
            Students stu = new Students();
            stu.setName("王小二");
            stu.setAge(22);
            stu.setBanji(3);

            studentsDao.insert(conn, stu);

            conn.commit();//提交事务


        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }



    }

}

从一名安卓开发工程师向javaweb工程师转变的第一天。
源代码:https://github.com/lgq895767507/JavaWebStudy/tree/master

你可能感兴趣的:(javaweb,java,jdbc)