Java-JDBC建立数据库连接(MySQL)
作者:mmseoamin日期:2023-12-25

注意:连接数据需要先在JAVA中导入mysql的jar包。

1、下载JAR包/导入JAR包:

1.1—下载JAR包

1、打开浏览器搜索MySQL,进入官网

2、点击DOWNLOADS 

 3、点击 MySQL Community (GPL) Downloads

 4、点击Connector/J

5、点击Archieve

6、选择版本,和OS,然后点击下载即可。         

版本号下载地址
8.0.32https://downloads.mysql.com/archives/get/p/3/file/mysql-connector-j-8.0.32.zip
5.1.30https://downloads.mysql.com/archives/get/p/3/file/mysql-connector-java-5.1.30.zip

 

1.2—导入JAR包

1、JAR包下载完成后,先解压文件。

2、进入到该文件夹,找到mysql-connector-java-version-bin.jar的文件,将该文件COPY到你的JAVA项目中的lib目录中(没有lib目录就新建个lib目录)。

3.IDEA开发软件中需要鼠标右键jar包,选择添加为库才能够进行使用

 

 

 

2.使用JDBC连接数据库

package jdbc;

import java.sql.*;

public class connect_it_zsgxlt {

    public static void main(String[] args) throws ClassNotFoundException, SQLException {

        // 1.加载驱动

        Class.forName("com.mysql.jdbc.Driver");

        // 2.连接信息-用户信息和URL 其他通用,其中it_zsglxt是数据库的名称

        String url = "jdbc:mysql://localhost:3306/it_zsglxt?useUnicode=true&characterEncoding=utf8&useSSL=true";

        //数据库管理用户名成和用户密码

        String user_name = "root";

        String user_pwd = "Csg0502!@#";

        //3.连接成功 数据库对象-数据库连接信息,数据库管理员账户,管路员密码,以下对象需要引入sql包,import java.sql.*;

        Connection connection = DriverManager.getConnection(url, user_name, user_pwd);

        //4.执行SQL的对象

        Statement statement = connection.createStatement();

        //statement.executeQuery();//查询操作,返回resultSet

        //statement.execute();//执行任何SQL 插入更新直接用upadte,execute执行还需要检索操作类型

        //statement.executeUpdate();//更新插入删除都是用这个

        //5.执行SQL的对象 去执行SQL

        String sql = "SELECT * FROM user_list"; //执行的sql语句

        System.out.println("执行SQL代码为:"+sql);

        ResultSet resultSet=statement.executeQuery(sql);//返回的结果集

        //resultSet.getObject()获取任意类型的数据,resultSet.getString();获取String类型的数据

        while (resultSet.next()){

            System.out.print("ID序列:"+resultSet.getInt("u_id")+" ");

            System.out.print("姓名:"+resultSet.getString("u_name")+" ");

            System.out.print("性别:"+resultSet.getString("sex")+" ");

            String name=resultSet.getString("u_name");

        }

        //6.释放连接 关闭结果集,关闭执行,关闭连接

        resultSet.close();

        statement.close();

        connection.close();

    }

}

 

3.创建JdbcUtils工具类,实现复用

新建个db.properties文件

 

 

jdbcutills类:

package mysql_db.utils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.net.PortUnreachableException;
import java.util.Properties;
public class JdbcUtils {
    private static String driver = null;
    private static String url = null;
    private static String username = null;
    private static String password = null;
    static {
        try {
            //1.input流加载db.properties文件
            InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
            //2.使用properties对象得到input流获取到的配置信息
            Properties properites = new Properties();
            properites.load(in);
            //3.信息获取
            driver = properites.getProperty("driver"); //获取驱动
            url = properites.getProperty("url");//获取连接信息
            username = properites.getProperty("username");//获取用户名
            password = properites.getProperty("password"); //获取密码
            Class.forName(driver); //加载驱动
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //获取连接
    public  static Connection   getConnection()throws SQLException{
      return DriverManager.getConnection(url,username,password);
    }
    //释放连接资源
    public static  void release(Connection conn,Statement st,ResultSet rs){
        if(rs!=null){
           try {
                rs.close();;
            }catch (SQLException e){
            }
        }
        if(st!=null){
            try {
                st.close();;
            }catch (SQLException e){
            }
        }
        if(conn!=null){
            try {
                conn.close();;
            }catch (SQLException e){
            }
        }
    }
}

测试类

 

package page.login;
import mysql_db.utils.JdbcUtils;
import java.sql.*;
//添加数据
public class login {
    public static void main(String[] args)  {
        Connection connection = null;
        Statement st = null;
        ResultSet rs = null;
        try {
            connection = JdbcUtils.getConnection(); //获取连接
            st=JdbcUtils.getConnection().createStatement(); //执行SQL的执行对象
            String sql="INSERT INTO user_list(id,`name`,`sex`,age,`address`) VALUES(1023,'JaKe Li','男',24,'南京')";
            int i= st.executeUpdate(sql);
            if(i>0){
                System.out.println("数据库操作完成!!!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            JdbcUtils.release(connection,st,rs);
            System.out.println("数据库断开连接!!!");
        }
    }
}