• JDBC访问数据库查询信息的步骤(硬编码格式)


    1 Class.forName()加载驱动

    2 DriverManager获取Connect连接

    3 创建Statement执行SQL语句

    4 返回ResultSet查询结果

    5释放资源

    package cn.tree.dao;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class MenuDao {
    
    	// 查询主目录
    	public void getMainList() {
    		Connection connection = null;
    		Statement st = null;
    		ResultSet rs = null;
    		try {
    			// 1、加载驱动
    			Class.forName("com.mysql.jdbc.Driver");
    			// 2、获取数据库连接
    			connection = DriverManager.getConnection(
    					"jdbc:mysql://127.0.0.1:3306/tree", "root", "123321");
    			// 3、获取Statement对象,执行sql语句
    			String sql = "select * from main";
    			st = connection.createStatement();
    			rs = st.executeQuery(sql);
    			// 4、处理sql执行结果
    			while (rs.next()) {
    				int id = rs.getInt("id");
    				String name = rs.getString("name");
    				System.out.println("id: " + id + "	" + "name: " + name);
    			}
    		} catch (ClassNotFoundException e) {
    			e.printStackTrace();
    		} catch (SQLException e) {
    			e.printStackTrace();
    		} finally {
    			try {
    				// 5、释放资源
    				rs.close();
    				st.close();
    				connection.close();
    			} catch (SQLException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    
    	public static void main(String[] args) {
    		MenuDao menuDao = new MenuDao();
    		menuDao.getMainList();
    	}
    }
    

      

  • 相关阅读:
    Ubuntu中Nginx的安装与配置
    在Ubuntu中安装Redis
    微博开放平台
    QQ互联 回调地址
    PostgreSQL在Ubuntu上安装指南
    postgresql常用命令
    在Linux下查看环境变量
    vue-04-组件
    vue-03-style与class
    vue-02-安装-指令
  • 原文地址:https://www.cnblogs.com/xtdxs/p/6506741.html
Copyright © 2020-2023  润新知