zoukankan      html  css  js  c++  java
  • java idea 连接数据库

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class QueryDemo {
    	public static void main(String[] args) throws Exception {
    		QueryDemo demo = new QueryDemo();
    		demo.findAllDept();
    	}
    	
    	//查找所有的部门
    	public void findAllDept() throws ClassNotFoundException, SQLException{
    		//1.注册数据库驱动
    		Class.forName("com.mysql.cj.jdbc.Driver");
    		//2.与数据库建立连接
    		Connection conn = DriverManager.getConnection(
    				"jdbc:mysql://@localhost:3306/oaec",
    				"root", "root");
    		//3.创建用来执行SQL语句的Statement对象
    		Statement stmt = conn.createStatement();
    		//4.执行SQL语句
    		String sql = "select id,name,region_id from s_dept";
    		//执行查询:executeQuery(String sql)==>ResultSet,结果集
    		//增删改:executeUpdate(String sql)==>int,影响的行数
    		ResultSet rs = stmt.executeQuery(sql);
    		//5.处理结果集(针对查询)
    		while(rs.next()) {
    			//一次循环处理一行
    			int id = rs.getInt(1);
    			String name = rs.getString(2);
    			int regionId = rs.getInt(3);
    			//展示简单输出
    			System.out.println(id+","+name+","+regionId);
    		}
    		//6.释放资源
    		//ResultSet-->Statement-->Connection
    		if(rs!=null) {
    			rs.close();
    		}
    		if(stmt!=null) {
    			stmt.close();
    		}
    		if(conn!=null) {
    			conn.close();
    		}
    	}
    }
    

      

    JDBC需要加到项目的外库中,否则不能连接.

  • 相关阅读:
    3D流水线
    log4cplus 配置文件的编写
    linux下的log4cplus的安装和使用
    日志信息的编写与调用
    转C++内存池实现
    转:自定义内存池的使用
    在linux查看内存的大小
    转:C++内存池
    数组指针 和指针数组的区别
    new的三种形态
  • 原文地址:https://www.cnblogs.com/alpha-cat/p/11393210.html
Copyright © 2011-2022 走看看