MYSQL(JDBC连接)

连接数据库主要分为六个步骤:

  1. 加载驱动
  2. 建立连接
  3. 准备SQL语句
  4. 执行SQL语句
  5. 处理结果
  6. 断开连接

我举一个查询的例子:

public static Connection lianJie() throws ClassNotFoundException, SQLException {
		//1.加载驱动
		Class.forName("com.mysql.cj.jdbc.Driver");
		
		String url = "jdbc:mysql://localhost:3306/mysql?serverTimezone=GMT%2B8";
		
		String user = "root";
		
		String password = "123456";
		//2.建立连接
		Connection connections = DriverManager.getConnection(url, user, password);
		//返回连接对象
		return connections;
		
	}

//调用它的方法如下:
public static void query(String query) throws SQLException, ClassNotFoundException {
		//获取connection对象
		Connection connection = DButil.lianJie();
		//3.准备SQL语句
		PreparedStatement pStatement = connection.prepareStatement(query);
		//4.执行SQL语句
		ResultSet resultSet = pStatement.executeQuery();
		//检索此 ResultSet对象的列的数量,类型和属性。
		ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
		//返回此 ResultSet对象中的列数。
		int column = resultSetMetaData.getColumnCount();
		System.out.println("序号" + "\t" + "姓名" + "\t" + "年龄" + "\t" + "课程");
		//5.处理结果遍历要查询的数据
		while (resultSet.next()) {
			//遍历行数
			for (int i = 1; i <= column; i++) {
				
				System.out.print(resultSet.getObject(i) + "\t");
				
			}
			System.out.println();
		}
		//6.关闭连接
			resultSet.close();
			pStatement.close();
			connection.close();

	}
	}


你可能感兴趣的:(数据库操作)