实习日志 - 第二天

文章目录

  • 摘要
  • 1. JDBC连接数据库
  • 2. 菜单输出以及查加改删

摘要

今天是来到宁波实习的第二天,主要工作是:使用JDBC连接MySQL数据库、编写控制台程序输出菜单并实现简单的增加、删除、更改、查询的数据库操作,以下是我对每个步骤的详细记录以及每个工作阶段的体会。

1. JDBC连接数据库

  1. 首先新建java工程后,下载要用到的jar包,并导入到工程;
  2. 然后进行数据库连接操作
//TestUser.java
package com.zhongruan;

import java.sql.*;

public class TestUser {
    final static String mysqlUrl = "jdbc:mysql://localhost:3306/java7?useSSL=true&characterEncoding=utf-8" +
            "&user=root&password=123";
            
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(mysqlUrl);
            System.out.println("MySQL connected successfully " + conn);
            String sql = "SELECT * FROM tb_user;";
            pstm = conn.prepareStatement(sql);
            rs = pstm.executeQuery();
            System.out.println("id\tusername\tpassword");
            while (rs.next()) {
                int id = rs.getInt(1);
                String username = rs.getString(2);
                String password = rs.getString(3);
                System.out.println(id + "\t" + username + "\t" + password + "\t");
            }
        } catch (Exception e) {
        } finally {
            try {
                if (rs != null){
                    rs.close();
                }else if (pstm != null) {
                    pstm.close();
                } else if (conn != null) {
                    conn.close();
                }
            } catch (Exception ex) {

            }
        }
    }
}
  1. 然后运行,得出结果
实习日志 - 第二天_第1张图片

这里由于每次操作都要使用到数据库连接、关闭语句,如果进行其他类型操作也会使用相似语句,因此可以进行代码重用进行改进。

  1. 对代码进行重用改造
/*DBUtil.java
 *进行操作封装
*/

package com.zhongruan;
import java.sql.*;

public class DBUtil {
    private static String driver = "com.mysql.jdbc.Driver";
    private static String url = "jdbc:mysql://localhost:3306/java7?useSSL=true&characterEncoding=utf-8";
    private static String user = "root";
    private static String password = "123";
    
    static {
        try {
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection() throws SQLException{
        Connection conn = null;
        conn = DriverManager.getConnection(url, user, password);
        System.out.println("MySQL connected successfully " + conn);
        return conn;
    }
    public static void closeConnection(ResultSet rs, PreparedStatement pstm, Connection conn)
            throws Exception {
        if (rs != null) {
            rs.close();
        } else if (pstm != null) {
            pstm.close();
        } else if (conn != null) {
            conn.close();
        }
    }
    public static void main(String[] args) {
        try {
            getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
/*User.java
 *Entity class
 *实体类 - 映射数据库字段
 */
package com.zhongruan;

public class User {
    private int id;
    private String username;
    private String password;

    public int getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

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

    public User(int id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public User() {
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}
/*TestUser2.java
 *代码重写后调用函数
 */
package com.zhongruan;

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

public class TestUser2 {
    Connection conn = null;
    PreparedStatement pstm = null;
    ResultSet rs = null;
    public void addUser(User user) {
        try {
            conn = DBUtil.getConnection();
            pstm = conn.prepareStatement("INSERT INTO tb_user(username,password) VALUES (?,?);");
            pstm.setString(1, user.getUsername());
            pstm.setString(2, user.getPassword());
            int executeResult = pstm.executeUpdate();
            if (executeResult > 0) {
                System.out.println("Add user successfully!");
            } else {
                System.out.println("Add user unsuccessfully!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                DBUtil.closeConnection(rs, pstm, conn);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        TestUser2 testUser2 = new TestUser2();
        User user = new User("张三", "123456");
        testUser2.addUser(user);
    }
}
  1. 很明显,代码重用之后,代码的逻辑结构更容易看懂,因此推荐第二种写法。

2. 菜单输出以及查加改删

  1. 代码过多,不易粘贴,直接看结果;
  2. 运行结果打印菜单如下:
实习日志 - 第二天_第2张图片
  1. 查加改删操作均能进行,因此今日任务完成,然后进行以后内容学习。

——2019.07.11 浙江.宁波

Will Also

你可能感兴趣的:(实习日志 - 第二天)