Java教程

JDBC-Java连接数据库

本文主要是介绍JDBC-Java连接数据库,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
package JDBC;

import java.sql.*;
/**
 *@author g0rez
 *@data 2021-08-07
 * 1.注册驱动(告诉Java程序,即将连接的是哪个品牌的数据库)
 * 2.获取连接(表示JVM的进程和数据库进程之间的通道打开了,这属于进程之间的通信,使用完后记得关闭通道)。
 * 3.获取数据库操作对象(专门执行sql语句的对象)
 * 4.执行SQL语句(DQL,DML…)
 * 5.处理查询结果集 (只有当第四步执行的是select语句的时候,才有本步)
 * 6.释放资源(使用完资源后一定要关闭资源,Java和数据库之间属于进程间的通信,开启之后一定要记得关闭)
 */
public class JDBCTest01 {
    public static void main(String[] args) {
        Connection con=null;
        Statement stm = null;
        ResultSet rs=null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_student","root","root");
            stm = con.createStatement();
            String sql = "select id,name,info from s_class";
            rs=  stm.executeQuery(sql);
            while (rs.next()){
                System.out.print(rs.getString(1)+" ");
                System.out.print(rs.getString(2)+" ");
                System.out.print(rs.getString(3));
                System.out.println();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (stm != null) {
                try {
                    stm.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

这篇关于JDBC-Java连接数据库的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!