java链接mysql,执行sql语句

链接mysql数据库

  • 准备官方库文件
    mysql-connector
  • 做连接前的准备工作
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtil {
    static String driverClassName=null;
    static String url=null;
    static String user=null;
    static String password=null;

    static {
        Properties properties=new Properties();
        try {
            //使用类加载器,加载类旁的配置文件
            InputStream inputStream= JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        driverClassName=properties.getProperty("driverClassName");
        url=properties.getProperty("url");
        user=properties.getProperty("user");
        password=properties.getProperty("password");
    }


    public static Connection createConnection(){
        Connection connection=null;
        try {
            //建立链接
            connection = DriverManager.getConnection(url, user, password);
        }  catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }


    public static void release(ResultSet rs, Statement st, Connection con){
        closeconn(con);closeRs(rs);closest(st);
    }

    public static void release(Statement st,Connection con){
        closeconn(con);closest(st);
    }

    private static void closeRs(ResultSet rs){
        try {
            if(rs!=null){
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            rs=null;
        }
    }

    private static void closest(Statement rs){
        try {
            if(rs!=null){
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            rs=null;
        }
    }

    private static void closeconn(Connection rs){
        try {
            if(rs!=null){
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            rs=null;
        }
    }
}

  • 把配置文件写出来放到资源文件夹下
    jdbc.properties
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://?????/??????useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT%2B8//此行问号代表ip与端口
user=????
密码 = ????
  • 正式访问
Connection connection =null;
Statement statement =null;
ResultSet re =null;
try {
	connection= JDBCUtil.createConnection();
	statement = connection.createStatement();
	statement.executeUpdate(这里是要执行的sql语句);

} catch (SQLException e) {
	e.printStackTrace();
}  finally {
	JDBCUtil.release(re,statement,connection);
}

你可能感兴趣的:(java链接mysql,执行sql语句)