JDBC连接数据库的操作

帅比萌擦擦* 提交于 2020-02-15 10:10:51

在连接数据库之前,应该先配置好MySQL的jar包
具体操作:File=>Project Setting=>Modules
在这里插入图片描述
点击“+”里面的JARs or Directories,找到下载好的jar包,在点击ok

JDBC连接数据库代码

import java.sql.*;

public class DBUtil2 {

    private static final String URL = "jdbc:mysql://localhost:3306/test";
    private static final String USER_NAME = "root";
    private static final String PASSWORD = "132173";
    private static volatile Connection connection=null;
    public static Connection getConnection(){
        if(connection==null){
            synchronized (DBUtil2.class){
                if(connection==null){
                    try {
                        Class.forName("com.mysql.jdbc.Driver");
                        System.out.println("数据库驱动加载成功");
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                        System.out.println("数据库驱动加载失败");
                    }
                    try {
                        connection= DriverManager.getConnection(URL,USER_NAME,PASSWORD);
                        System.out.println("数据库连接成功");
                    } catch (SQLException e) {
                        e.printStackTrace();
                        System.out.println("数据库连接失败");
                    }
                }
            }
        }
        return connection;
    }
    public static void close(Connection connection, Statement statement, ResultSet resultSet){
        try {
            if(resultSet!=null){
                resultSet.close();
            }
            if(statement!=null){
                statement.close();
            }
            if(connection!=null){
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw  new RuntimeException("数据库资源释放失败");
        }
    }
    public static void close(Connection connection,Statement statement){
        close(connection,statement,null);
    }

应用实例:

 public static void creatTable(){
        Connection connection=null;
        Statement statement=null;
        ResultSet resultSet=null;
        try {
            connection=DBUtil.getConnection();
            statement=connection.createStatement();
            String sql="use hello;";
            String sql1="drop table if exists person;";
            String sql2="create table if not exists person(id int,name varchar(50));";
            String sql3="insert into person values(1,'lisi')";
            statement.execute(sql);
            statement.execute(sql1);
            statement.execute(sql2);
            statement.execute(sql3);
            System.out.println("表格创建成功");
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,statement,resultSet);
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!