使用JDBC向数据库中插入一条数据

原谅我是初学者,这个方法写的很烂,以后不会改进,谢谢

/**
     * 通过JDBC向数据库中插入一条数据 1.Statement 用于执行SQL语句的对象 1.1 通过Connection 的
     * createStatement() 方法来获取 1.2 通过executeUpdate(sql) 的方法来执行SQL 1.3
     * 传入的SQL可以是INSERT/UPDATE/DELETE,但不能是SELECT
     * 
     * 2.Connection和Statement使用后一定要记得关闭 需要在finally里关闭其对象
     * 2.1 关闭的顺序:先关闭后获取的
     */
    @Test
    public void testStatement() {
        // 1.获取数据库连接
        Connection connection = null;
        // 4.执行插入
        // 4.1 获取操作SQL语句的Statement对象:
        // 调用Connection的createStatement()方法来创建Statement的对象
        Statement statement = null;
        try {
            connection = getConnection();

            // 3.准备插入的SQL语句
            String sql = "INSERT INTO customers (NAME,EMAIL,BIRTH) " 
                    +"VALUES ('李小龙','long@live.com','1940-11-27')";

            statement = connection.createStatement();

            // 4.2 调用Statement对象的executeUpdate(sql) 执行SQL 语句的插入
            statement.executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 5.关闭Statement对象
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                // 2.关闭连接
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public Connection getConnection() throws Exception {
        // 准备连接数据库的四个字符串
        // 驱动的全类名
        String driverClass = null;
        String jdbcUrl = null;
        String user = null;
        String password = null;
        String jdbcName = null;
        // 读取jdbcName.properties文件
        InputStream inStream = getClass().getClassLoader().getResourceAsStream("properties/jdbcName.properties");
        Properties propertiesOfName = new Properties();
        propertiesOfName.load(inStream);
        jdbcName = propertiesOfName.getProperty("jdbcName");
        // 读取需要的properties 文件
        InputStream in = getClass().getClassLoader().getResourceAsStream("properties/" + jdbcName + ".properties");
        Properties properties = new Properties();
        properties.load(in);
        driverClass = properties.getProperty("driver");
        jdbcUrl = properties.getProperty("jdbcUrl");
        user = properties.getProperty("user");
        password = properties.getProperty("password");

        // 加载数据库驱动程序(注册驱动)
        Class.forName(driverClass);

        Connection connection = DriverManager.getConnection(jdbcUrl, user, password);
        return connection;
    }

数据库配置如下

 

原文地址:https://www.cnblogs.com/gode/p/5820134.html