微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用JAVA jdbc编写一段快速连接Mysql数据库

使用JAVA jdbc编写一段快速连接MysqL数据库

第一次写文档,看的人轻喷。做一个简单记录

话不多说,下面直接上代码

public static void main(String[] args) {
        Connection conn = null;
        String sql;
//        String url = "jdbc:MysqL://localhost:3306/test?" +
//                "user=root&password=root&useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT";
        String url = "jdbc:MysqL://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT";
        String user = "root";
        String password = "root";
        try {
            Class.forName("com.MysqL.jdbc.Driver");
            log.info("成功加载MysqL驱动程序");
            conn = DriverManager.getConnection(url, user, password);
            Statement stmt = conn.createStatement();
            sql = "create table student(No char(30), name varchar(30), primary key(No))";
            int result = stmt.executeUpdate(sql);
            if (result != -1) {
                log.info("创建数据表成功");
                sql = "insert into student(no, name) values ('201901', 'sui123')";
                result = stmt.executeUpdate(sql);
                sql = "insert into student(no, name) values ('201902', 'ya123')";
                result = stmt.executeUpdate(sql);
                sql = "select * from student";
                ResultSet rs = stmt.executeQuery(sql);
                while (rs.next()) {
                    log.info(rs.getString(1) + "\t" + rs.getString(2));
                }
            }
        } catch (ClassNotFoundException e) {
            log.error("没有找到驱动类");
            throw new RuntimeException("没有找到加载类");
        } catch (sqlException e) {
            log.error("sql不正确", e.getMessage(), e);
            throw new RuntimeException("sql不正确");
        } finally {
            try {
                conn.close();
            } catch (sqlException e) {
                log.error("关闭连接失败");
                throw new RuntimeException("关闭连接失败");
            }
        }
    }

这样

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐