当前位置:   article > 正文

MySQL数据库与java代码的连接_mysql连接java的包

mysql连接java的包

基础链接的八个步骤

  1. 导入jar包

    把jar包文件复制导入刚刚创建的项目的src里面

    • 注:同一项目下该操作执行一次即可
  2. 加载驱动

    Class.forName("com.mysql.cj.jdbc.Driver");
    
    • 1
    • 注:此处括号内的写法与jar包版本有关,如果导入的jar包在6版本以上,一般采用上述的写法,反之,则使用"com.mysql.jdbc.Driver"。
  3. 获取并创建数据库连接对象

    //创建完成后该对象将会自动打开通道
    Connection conn;
    //localhost可以替换为127.0.0.1,选择自己习惯的即可
    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","123");
    //三个参数分别为		选择连接的数据库(localhost:3306/后接数据库名称)	用户名	密码
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 注:该操作一般分为获取和创建两步来写能够便于后期的维护与实际操作。
  4. 定义一个要执行的sql语句

    String sql = "select * from student";
    
    • 1
  5. 获取并创建sql语句执行对象

    Statement stmt = null;
    stmt = conn.createStatement();
    
    • 1
    • 2
    • 注:与数据库连接对象的创建同理
  6. 给执行对象传入sql执行语句

    stmt.executeQuery(sql);
    
    • 1
    • 注:执行对象调用的方法与传入的sql语句有关,可以简单分为增删改(会使表内容发生变化的)语句使用executeUpdate(),返回的是sql语句执行后返回的受影响行数;查询语句使用executeQuery(),返回的是查询到的表所对应的结果集。
  7. 处理执行后返回的结果

    //根据需要处理即可,一般先使用变量进行接收,之后进行具体操作
    ResultSet rs = stmt.executeQuery(sql);
    
    • 1
    • 2
  8. 关闭流通道释放资源

    //原则上,后创建的先关闭,先创建的后关闭
    rs.close();
    conn.close();
    stmt.close();
    
    • 1
    • 2
    • 3
    • 4

以上为步骤的简写,整体写法如下,供应参考:

import java.sql.*;

public class JDBCPractice {
    public static void main(String[] args) throws Exception{
        jdbc();
    }

    private static void jdbc() throws Exception {
        //2.注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //3.获取并创建数据库连接对象
        Connection conn;
        conn = DriverManager.getConnection(
        "jdbc:mysql://127.0.0.1:3306/test","root","123");
        //4.创建sql语句
        String sql = "select * from student";
        //5.获取并创建sql语句执行对象
        Statement stmt;
        stmt = conn.createStatement();
        //6.给执行对象传入sql执行语句
        //7.处理返回结果
        ResultSet rs = stmt.executeQuery(sql);
        while(rs.next()){
            System.out.println(rs.getString("name"));
        }
        //8.关闭流通道,释放资源
        rs.close();
        stmt.close();
        conn.close();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

实际操作中的数据库操作

  • 以上为数据库连接的详细步骤,但在实际运用中,为了避免代码冗长会简化上述步骤,将数据库的连接信息存入一个properties文件中,并将对于数据库的操作写在同一个Dao类中。在其他代码执行对数据库操作时,直接调用本类方法即可。并且为了节约内存的使用,每次执行操作后会把流通道全部关闭减少内存占用,提高程序运行效率。
  • properties文件样式如下:
    (调用信息的名称=信息)
    driver=com.mysql.cj.jdbc.Driver
    url=jdbc:mysql://127.0.0.1:3306/student
    user=root
    pwd=123
    
    • 1
    • 2
    • 3
    • 4
  • Dao类下包含有初始化、打开连接、关闭连接以及增删改操作和查询操作分别作为四个方法写出:
    1. 初始化(需要在程序执行前准备好)

      //导入.properties结尾的配置文件信息
      static{
          private String url;
          private String user;
          private String pwd;
          private String driver;
      	Properties properties = new Properties();
      	InputStream is = new InputStream(类名.class.getClassLoader()
      		.getSourceAsStream("配置文件名称.properties"));
      	try{
              properties.load(is);
          }catch (Exception e){
              System.out.println(e.getMessage());
          }
          url=properties.getProperty("url");
          user=properties.getProperty("user");
          pwd=properties.getProperty("pwd");
          driver=properties.getProperty("driver");
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
    2. 打开连接

       public Connection openConn(){
      	Connection conn = null;
          try{
              //加载驱动程序
              Class.forName(driver);
              conn = DriverManager.getConnection(url,user,pwd);
          }catch (Exception e){
              System.out.println(e.getMessage());
          }finally{
              return conn;
         }
       }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
    3. 关闭连接

      public void colseConn(Connection conn, PreparedStatement pstmt,ResultSet rs){
      	       try{
      	       		//判断对象是否为空,为空则进行关闭,不为空不执行操作即可
      	           if (rs!=null){rs.close();}
      	           if (pstmt!=null){pstmt.close();}
      	           if (conn!=null){conn.close();}
      	       }catch (Exception e){
      	           System.out.println(e.getMessage());
      	       }
              }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
    • 注:该方法中使用的PreparedStatement对象与Statement的基本功能一致
    1. 增删改操作

      //执行指定语句操作,返回执行后受影响行数
      public int update(String sql) {
              int line = 0;
              Connection conn = openConn();
              try{
                  PreparedStatement pstmt = conn.prepareStatement();
                  line = pstmt.executeUpdate(sql);
                  colseConn(conn,pst,null);
              }catch (Exception e){
                  System.out.println(e.getMessage());
              }finally{
      	        return line;
              }
          }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
    2. 查询操作

      //执行指定语句操作,返回执行后查询到的表对应数据集
      public ResultSet query(String sql) {
          Connection conn = openConn();
          ResultSet rs = null;
          try{
              PreparedStatement pstmt = conn.prepareStatement();
              rs = pst.executeQuery(sql);
              //此处不进行关闭数据流通道操作,返回数据操作与rs对象挂钩,关闭后无法使用
              //在程序执行后依会关闭通道
          }catch (Exception e){
              System.out.println(e.getMessage());
          }finally{
              return rs;
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15

将数据库与java代码连接可以让你的程序储存一些用户所需要的数据,希望这篇文章对你的开发能有所帮助。——weakest

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/天景科技苑/article/detail/738209
推荐阅读
相关标签
  

闽ICP备14008679号